There are two different ways to set up a many-to-many association in Rails. In this episode you will see how to implement both ways along with some tips on choosing the right one for your project.
has_and_belongs_to_many
has_many :through
has_and_belongs_to_many
# in migration
def self.up
create_table 'categories_products', :id => false do |t|
t.column :category_id, :integer
t.column :product_id, :integer
end
end
# models/product.rb
has_and_belongs_to_many :categories
# models/category.rb
has_and_belongs_to_many :products
has_many :through
# models/categorization.rb
belongs_to :product
belongs_to :category
# models/product.rb
has_many :categorizations
has_many :categories, :through => :categorizations
# models/category.rb
has_many :categorizations
has_many :products, :through => :categorizations
本文介绍在Rails中实现多对多关联的两种方法:has_and_belongs_to_many和has_many-through,并提供代码示例帮助理解如何选择合适的关联方式。

被折叠的 条评论
为什么被折叠?



