Has_Many:通过或:finder_sql [英] Has_Many :Through or :finder_sql

查看:48
本文介绍了Has_Many:通过或:finder_sql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经确定了我想要的东西,但是我似乎无法以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):

人类 关系(父母,后代)

Human Relationships (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中忽略了外键(根据此处的文档:

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:

DEPRECATION警告:基于字符串 关联插值 条件已弃用.请使用 proc代替.因此,例如 has_many:older_friends,:conditions =>'age>#{age}'应该更改为has_many:older_friends,:conditions => proc {"age>#{age}"}. (从(irb):1的irb_binding调用)

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)

但是,无论我如何在这里攻击: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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆