加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Has_Many:通过或:finder_sql

发布时间:2020-12-16 22:09:59 所属栏目:百科 来源:网络整理
导读:我已经确定了我想要的东西,但是我似乎无法按照钢轨设计师的要求来找到它.基本上,我有(请搁置复数/等问题): 人的 关系(父母,子孙) 我试图让一个父母的所有后代,以及许多后代的单亲(假定每个后代只有一个父母). 我可以通过以下方式在模型中做到这一点: has_o
我已经确定了我想要的东西,但是我似乎无法按照钢轨设计师的要求来找到它.基本上,我有(请搁置复数/等问题):

人的
关系(父母,子孙)

我试图让一个父母的所有后代,以及许多后代的单亲(假定每个后代只有一个父母).

我可以通过以下方式在模型中做到这一点:

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)

但是,现在我得到这个错误:

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)

然而,无论我如何闯入:条件在这里,似乎没有: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}" }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读