【发布时间】:2013-11-14 01:56:11
【问题描述】:
我是 Rails 新手,我正在尝试了解 Rails 协会的工作原理。除了上面提到的2个之外,我能够理解所有的关联。
到底在哪里以及为什么使用 has_many :through 和 has_and_belongs_to_many 关联?
请根据场景提供最简单的答案
【问题讨论】:
标签: ruby-on-rails-3 associations
我是 Rails 新手,我正在尝试了解 Rails 协会的工作原理。除了上面提到的2个之外,我能够理解所有的关联。
到底在哪里以及为什么使用 has_many :through 和 has_and_belongs_to_many 关联?
请根据场景提供最简单的答案
【问题讨论】:
标签: ruby-on-rails-3 associations
来自文档:
Choosing Between has_many :through and has_and_belongs_to_many
ActiveRecord Association Basics
最简单的经验法则是,如果您需要将关系模型作为独立实体使用,您应该设置一个 has_many :through 关系。如果您不需要对关系模型进行任何操作,那么设置 has_and_belongs_to_many 关系可能会更简单(尽管您需要记住在数据库中创建连接表)。
如果您需要验证、回调或连接模型上的额外属性,您应该使用 has_many :through。
【讨论】:
has_and_belongs_to_many 是 Rails 1 的遗物。没有理由使用它。与has_many :through which they're getting rid of in master 相比,它遵循一个单独的、受支持较少且问题较多的代码路径:
has_and_belongs_to_many 现在通过 has_many :through 透明地实现。行为应该保持不变,如果不是,这是一个错误。
你可以用has_and_belongs_to_many 做任何你可以用has_many :through 做的事情如果我要发布代码示例,我只会解释has_and_belongs_to_many 的局限性。
【讨论】:
default_scope。
我会检查这个Railscast。 Ryan Bates 真是一位了不起的老师:)
【讨论】:
两者都用于相同的目的,即在 rails 中创建 many_to_many 关系。只是他们有不同的语法。假设有两个表 Product 和 Category ,如果我们想在这两个表之间创建 many_to_many 关系,那么我们应该这样做:
has_and_belongs_to_many
迁移中
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:通过
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
现在开发人员使用 has_many :through 来创建 many_to_many 关系,因为它不那么复杂且易于使用
【讨论】: