【问题标题】:Setting a :has_many :through association on a belongs_to association Ruby on Rails设置 :has_many :through 关联的 belongs_to 关联 Ruby on Rails
【发布时间】:2011-04-21 07:38:57
【问题描述】:

我有三个模型,每个模型都有以下关联:

class Model1 < ActiveRecord::Base
  has_many :model2s
  has_many :model3s
end

class Model2 < ActiveRecord::Base
  belongs_to :model1
  has_many :model3s, :through => :model1  # will this work? is there any way around this?
end

class Model3 < ActiveRecord::Base
  belongs_to :model1
  has_many :model2s, :through => :model1  # will this work? is there any way around this?
end

正如您在评论文本中看到的那样,我已经提到了我需要的内容。

【问题讨论】:

    标签: ruby-on-rails ruby associations has-many-through belongs-to


    【解决方案1】:

    您只需创建访问它的方法

    class Model2 < ActiveRecord::Base
      belongs_to :model1
    
      def model3s
        model1.model3s
      end
    end
    

    或者,您可以将model3s方法委托给model1

    class Model2 < ActiveRecord::Base
      belongs_to :model1
    
      delegate :model3s, :to => :model1
    
    end
    

    【讨论】:

    • 委托部分给了我这个错误“委托需要一个目标。提供一个带有 :to 键作为最后一个参数的选项哈希(例如委托 :hello, :to => :greeter)。”。让我试试方法部分
    • 第一种方法是做好事,解决我的问题。但是请在委托机制中找到一些调整并编辑答案。 :D
    • 使用委托 :model3s, :to => :model1 代替委托 :model3s, :as => :model1。 :D 为我工作
    • 你说得对。有时我需要在回答之前检查文档。
    • 作为更新,从 Rails 4.2 开始,您现在可以通过 belongs_to 关系执行 has_manyhas_one
    【解决方案2】:

    为什么不试试:

    class Model1 < ActiveRecord::Base
      has_many :model2s
      has_many :model3s
    end
    
    class Model2 < ActiveRecord::Base
     belongs_to :model1
     has_many   :model3s, :primary_key => :model1_id,
                          :foreign_key => :model1_id
    
    end
    
    class Model3 < ActiveRecord::Base
      belongs_to :model1
      has_many   :model2s, :primary_key => :model1_id,  
                           :foreign_key => :model1_id
    end
    

    这将通过 model1_id 将 model2 和 model3 连接到活动记录中,而将 model1 完全排除在外,并且应该更有效。

    【讨论】:

    • 在一般情况下,这将失去附加到 Model1 中“has_many”定义的任何条件。例如如果 Model1 是用 has_many :model2s, -&gt; {where deleted: false} 定义的,那么如果不编写一些可能很脆弱和/或冗长的额外代码,您就不会选择这些条件。只是需要注意的事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    • 2015-12-17
    相关资源
    最近更新 更多