Found this railscast helpful in trying to understand many to many relationships in ror. And the difference between using has_and_belongs_to_many and the has_many :through. As noted in the railscast, the has_and_belongs_to_many to very limited and does not allow as many options as has_many :through. Due to Ryan’s recommendation in the railscast, I’m going to use the has_many :through.
From the tutorial, here’s an example of how to do many to many.
has_and_belongs_to_many example using Product and Category model (I’ve updated it to use Rails 3)
type in the command the following:
>> rails generate model category name:string
>> rails generate model product name:string
>> rails generate migration create_categories_products_join
add to CreateCategoriesProducts migration file
class CreateCategoriesProductsJoin < ActiveRecord::Migration def self.up create_table 'categories_products', :id => false do |t| t.column 'category_id', :integer t.column 'product_id', :integer end end def self.down drop_table 'categories_products' end end
>> rake db:migrate
and set up the has_and_belongs_to_many associations in both the Product and Category models.
has_many :through example
Create a model at the command line
>> rails generate model categorization product_id:integer category_id:integer
*note you can add more columns to the model if needed
In your models add the following
class Categorization < ActiveRecord::Base belongs_to :product belongs_to :category end class Product < ActiveRecord::Base has_many :categorizations has_many :categories, :through => :categorizations end class Category < ActiveRecord::Base has_many :categorizations has_many :products, :through => :categorizations end
Ryan ends the railscast by adding some helpful hints when trying to decide between the two. He suggests asking yourself two questions.
1)Do I need to store extra information in the join?
2)Do I need to treat the join like its own model?
If you answer yes to any of the above, he suggests using the has_many :through association. Otherwise he suggests a strong “might” to use the has_and_belongs_to_many associations. He warns that this association is very limited.