【问题标题】:Difference between has_many :through and has_and_belongs_to_many in layman's termshas_many :through 和 has_and_belongs_to_many 之间的区别用外行的话来说
【发布时间】:2013-11-14 01:56:11
【问题描述】:

我是 Rails 新手,我正在尝试了解 Rails 协会的工作原理。除了上面提到的2个之外,我能够理解所有的关联。

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

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

【问题讨论】:

    标签: ruby-on-rails-3 associations


    【解决方案1】:

    来自文档:

    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。

    【讨论】:

      【解决方案2】:

      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
      【解决方案3】:

      我会检查这个Railscast。 Ryan Bates 真是一位了不起的老师:)

      【讨论】:

      • 最好提供实际文本和答案,链接可能不会永远打开。
      【解决方案4】:

      两者都用于相同的目的,即在 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 关系,因为它不那么复杂且易于使用

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-11
        • 2016-05-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多