1

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

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

那么问题是如何添加:combined结合两者的第三个关联?我知道这可以用 a 来完成,:finder_sql并且可以用 a 来实现类似的结果scope,但是这些都没有给我一个实际的关联。这样做的全部意义在于能够将其用于另一个关联,:through例如Model.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

谢谢。

4

1 回答 1

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
于 2012-09-28T09:24:25.867 回答