【发布时间】:2011-07-24 20:29:05
【问题描述】:
我已经确定了我想要的东西,但我似乎无法以 Rails 设计师正在寻找的方式得到它。基本上,我有(请搁置多元化/等问题):
人类 关系(父母、后代)
我正在尝试为单亲获取所有后代,并为许多后代获取单亲(假设每个后代只有一个父母)。
我可以在模型中通过以下方式做到这一点:
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)
但是,现在我收到了这个错误:
弃用警告:基于字符串 关联插值 条件已弃用。请使用一个 proc 代替。所以,例如, has_many :older_friends, :conditions => 'age > #{age}' 应该改为 has_many :older_friends, :conditions => 过程{“年龄>#{年龄}”}。 (在 (irb):1 从 irb_binding 调用)
但是,无论我如何破解 :conditions ,似乎 :finder_sql 都不想参与。有什么想法吗?
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 has-many-through