开发者

Rails : Model with Array of object of my class

开发者 https://www.devze.com 2023-04-09 03:41 出处:网络
I\'m beginning RoR. I\'ve designed my model like this : User -login:string -password:string -email:string

I'm beginning RoR. I've designed my model like this :

User -login:string -password:string -email:string -followers:array (type user)

I hav开发者_如何转开发e now this termainal rails command :*

rails generate model User login:string password:string email:string

but i don't know how to tell my generated model that I would like an array of User.

I think my question is a bit stupid because Ruby is like PHP (no type). But I prefer to ask ... Thanks for your help !


If you want to have something like followers you have to use a many-to-many association. Take a look at associations in the rails guide : http://guides.rubyonrails.org/association_basics.html

You have to remember that when you generate a model and you specify login:string for example you specify the name and the type of the column which will be created in your database.

The right way is to have a many-to-many relationship. You have to say that your User has_and_belongs_to_many followers (I assume if a Use has many followers he can follow many User?). You will need to create an other table which will associate a user to another.

You'll find many articles on google which explain how to create many to many relationship. But RailsGuides are really well done, take a look at it first.

Edit:

As your follower will be also be of type User, you'll have to do something like that: has_and_belongs_to_many :followers, :class_name => "User" You can take a look at the documentation for other options: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_and_belongs_to_many

0

精彩评论

暂无评论...
验证码 换一张
取 消