ruby-on-rails – Has_Many:通过或:finder_sql
我已经确定了我想要的东西,但是我似乎无法按照钢轨设计师的要求来找到它.基本上,我有(请搁置复数/等问题):
人的 我试图让一个父母的所有后代,以及许多后代的单亲(假定每个后代只有一个父母). 我可以通过以下方式在模型中做到这一点: 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,:foreign_key => :source_human_id,:source => :human 是不可能的,因为外键在has_many中被忽略(根据这里的文档:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many) 但是,现在我得到这个错误:
然而,无论我如何闯入:条件在这里,似乎没有: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}" } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |