【问题标题】:How to combine two has_many associations into one?如何将两个 has_many 关联合二为一?
【发布时间】:2012-09-28 09:00:52
【问题描述】:

这似乎是一个相当普遍的问题,但没有明确的解决方案。再次重申,假设我有一个模型:

def Model < ActiveRecord::Base
    has_many :somethings, ...
    has_many :otherthings, ...
end

那么问题是如何添加结合两者的第三个关联:combined?我知道这可以用:finder_sql 来完成,类似的结果可以用scope 来实现,但是这些都没有给我一个实际的关联。这样做的重点是能够将其用于与:throughModel.first.combined.some_scope.count 之类的另一个关联

编辑:实际代码的相关部分

class Donation < ActiveRecord::Base
    # either Project or Nonprofit       
    belongs_to :donatable, :polymorphic => true
    belongs_to :account
end

class Project < ActiveRecord::Base
    belongs_to :nonprofit
end

class Nonprofit < ActiveRecord::Base
    has_many :projects

    # donations can be either direct or through a project
    # the next two associations work fine on their own

    # has_many :donations, :as => :donatable, :through => :projects
    # has_many :donations, :as => :donatable

    has_many :donations, ....                       # how do I get both here,
    has_many :supporters, :through => :donations    # for this to work?
end

谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord associations


    【解决方案1】:

    如果 SomethingOtherthing 足够相似,请使用 STI:

    def Model < ActiveRecord::Base
      has_many :somethings
      has_many :otherthings
      has_many :genericthings
    end
    
    def Genericthing < Activerecord::Base
      # put a string column named "type" in the table
      belongs_to :model
    end
    
    def Something < Genericthing
    end
    
    def Otherthing < Genericthing
    end
    

    【讨论】:

    • 它们是相同的东西,已经在使用 STI,但其中一个来自 :through 一个不同的模型。在那个自定义 :finder_sql 中,我会使用 LEFT JOIN 和 OR 子句。
    • 请更加明确,将您的中间模型添加到原始问题中,以便每个人都知道要解决哪个问题。
    猜你喜欢
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多