我已经确定了我想要的东西,但我似乎无法以 Rails 设计师正在寻找的方式获得它。基本上,我有(请搁置多元化/等问题):
人类 关系( parent 、后代)
我正在尝试获取单亲的所有后代,以及许多后代的单亲(假设每个后代只有一个 parent )。
我可以在模型中通过以下方式做到这一点:
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}'
我必须这样做,因为更好的方法是:
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)
但是,现在我收到了这个错误:
DEPRECATION WARNING: String-based interpolation of association conditions is deprecated. Please use a proc instead. So, for example, has_many :older_friends, :conditions => 'age > #{age}' should be changed to has_many :older_friends, :conditions => proc { "age > #{age}" }. (called from irb_binding at (irb):1)
但是,无论我如何破解 :conditions ,似乎 :finder_sql 都不想参与。有什么想法吗?
最佳答案
如果你这样做会怎样
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}" }
关于ruby-on-rails - Has_Many :Through or :finder_sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5465674/