Monday, 15 September 2014

Creating a many-to-many relation in Rails -



Creating a many-to-many relation in Rails -

so i'm rails n00b , want create "favorites" relationship such user can have many favorite item. i'm not exclusively sure how this, how i'm going seek i'm not sure if practice @ all:

class user < activerecord::base has_many :favorites //other code end class favorite < activerecord::base belong_to :user has_one :item end class item < activerecord::base belongs_to :item end

is way it? should using has_and_belongs_to_many ? i'm specially concerned in next scenario: user has 100 favorite items. when user.find(id) retrieving 100 favorites , 100 items?

in case it's important: ruby version 1.9.3, rails version 3.2.11

in case has_many :through way go. recommend reading: http://guides.rubyonrails.org/association_basics.html

of particular involvement regard question:

2.8 choosing between has_many :through , has_and_belongs_to_many

rails offers 2 different ways declare many-to-many relationship between models. simpler way utilize has_and_belongs_to_many, allows create association directly:

class assembly < activerecord::base has_and_belongs_to_many :parts end class part < activerecord::base has_and_belongs_to_many :assemblies end

the sec way declare many-to-many relationship utilize has_many :through. makes association indirectly, through bring together model:

class assembly < activerecord::base has_many :manifests has_many :parts, :through => :manifests end class manifest < activerecord::base belongs_to :assembly belongs_to :part end class part < activerecord::base has_many :manifests has_many :assemblies, :through => :manifests end

the simplest rule of thumb should set has_many :through relationship if need work relationship model independent entity. if don’t need relationship model, may simpler set has_and_belongs_to_many relationship (though you’ll need remember create joining table in database).

you should utilize has_many :through if need validations, callbacks, or attributes on bring together model.

ruby-on-rails ruby-on-rails-3

No comments:

Post a Comment