0

我是 Rails 新手,我正在尝试了解 Rails 协会是如何工作的。我能够理解除上述两个之外的所有关联。

在哪里以及为什么使用 has_many :through 和 has_and_belongs_to_many 关联?

请根据场景提供最简单的答案

4

4 回答 4

1

has_and_belongs_to_many是 Rails 1 的遗物。没有理由使用它。它遵循一个单独的、受支持较少且问题较多的代码路径,而不是has_many :through 他们在 master 中摆脱的代码路径:

has_and_belongs_to_many 现在通过 has_many :through 透明地实现。行为应该保持不变,如果不是,这是一个错误。

如果has_and_belongs_to_manyhas_many :through要发布代码示例,我只会解释has_and_belongs_to_many.

于 2013-11-03T14:10:05.763 回答
1

从文档:

在 has_many :through 和 has_and_belongs_to_many 之间进行选择

ActiveRecord 关联基础

最简单的经验法则是,如果您需要将关系模型作为独立实体使用,则应该设置一个 has_many :through 关系。如果您不需要对关系模型做任何事情,那么设置 has_and_belongs_to_many 关系可能会更简单(尽管您需要记住在数据库中创建连接表)。

如果您需要验证、回调或连接模型上的额外属性,您应该使用 has_many :through。

于 2013-11-03T12:51:02.257 回答
0

两者都用于相同的目的,即在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    

模型/product.rb

has_and_belongs_to_many :categories

模型/类别.rb

has_and_belongs_to_many :products

has_many:通过

模型/分类.rb

belongs_to :product
belongs_to :category

模型/product.rb

has_many :categorizations
has_many :categories, :through => :categorizations

模型/类别.rb

has_many :categorizations
has_many :products, :through => :categorizations

现在开发人员使用 has_many :through 来创建 many_to_many 关系,因为它不那么复杂且易于使用

于 2014-04-07T13:24:13.460 回答
0

我会检查这个Railscast。瑞恩贝茨真的是一位了不起的老师:)

于 2013-11-03T12:36:06.527 回答