问题描述
我已经确定了我想要的东西,但是我似乎无法以Rails设计师正在寻找的方式来获得它.基本上,我有(请撇开复数/等问题):
I've nailed down what I want, but I can't seem to get it in a way that the rails designers are looking for. Basically, I have (please set aside pluralization/etc issues):
人类关系(父母,后代)
HumanRelationships (Parent, Offspring)
我正在尝试为单亲获得所有后代,并为许多后代获得单亲(假设每个后代只有一个亲本).
I'm trying to get all the offsprings for a single parent, and the single parent for many offsprings (assume only one parent per offspring).
我可以在模型中以以下方式执行此操作:
I can do this in the following way in the model:
has_one :parent, :through => :relationships, :foreign_key => :human_id, :source => :source_human
has_many :offsprings, :finder_sql =>
'SELECT DISTINCT offsprings.* ' +
'FROM humans offsprings INNER JOIN relationships r on ' +
'r.human_id = offsprings.id where r.source_human_id = #{id}'
我必须这样做,因为更好的方法是这样:
I had to do this, because the nicer way to do it:
has_many :offsprings, :through => :relationships, :foreign_key => :source_human_id, :source => :human
这是不可能的,因为在has_many中忽略了外键(根据此处的文档: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many )
Is not possible because foreign keys are ignored in has_many (according to the docs here: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many)
但是,现在出现此错误:
However, now I'm getting this error:
但是,无论我如何在这里攻击:condition,似乎:finder_sql都不希望参与.有什么想法吗?
However, no matter how I hack at :conditions here, it does not appear that :finder_sql wants to participate. Any thoughts?
推荐答案
该怎么办
has_many :offsprings, :finder_sql =>
proc { "SELECT DISTINCT offsprings.* " +
"FROM humans offsprings INNER JOIN relationships r on " +
"r.human_id = offsprings.id where r.source_human_id = #{id}" }
这篇关于Has_Many:通过或:finder_sql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!