This seems to be a fairly common problem over here, yet there is no definitive solution. To restate once again, say I have a model:
这似乎是一个相当普遍的问题,但没有确定的解决方案。再次重申,说我有一个模型:
def Model < ActiveRecord::Base
has_many :somethings, ...
has_many :otherthings, ...
end
The question is then how to add a third association :combined
that combines the two? I know this can be done with :finder_sql
and similar result can be achieved with a scope
, but neither of these gives me an actual association. The whole point of this is to be able to use it for another association with :through
and things like Model.first.combined.some_scope.count
问题是如何添加第三个关联:结合两者?我知道这可以用:finder_sql和类似的结果可以用范围实现,但这些都没有给我一个实际的关联。这一点的重点是能够将它用于另一个关联:通过和类似Model.first.combined.some_scope.count之类的东西
EDIT: the relevant portions of the actual code
编辑:实际代码的相关部分
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
Thanks.
谢谢。
1 个解决方案
#1
1
If Something
and Otherthing
are sufficiently similar, use STI:
如果Something和Otherthing足够相似,请使用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
#1
1
If Something
and Otherthing
are sufficiently similar, use STI:
如果Something和Otherthing足够相似,请使用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