ruby-on-rails - Has_Many :Through or :finder_sql

标签 ruby-on-rails ruby ruby-on-rails-3 has-many-through

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

相关文章:

ruby-on-rails - 在包含在类中的模块中使用 define_method?

ruby-on-rails - Model.first 不从表中检索第一条记录

ruby-on-rails - 如何在 Rails 应用程序中运行视频流

ruby-on-rails - 运行 Rspec 时出现 "No such file to load"错误

ruby-on-rails - 无法构建 gem native 扩展。(extconf 失败)

ruby-on-rails-3 - 如何向 ActiveRecord::Base 添加方法?

ruby-on-rails - RoR rspec 测试失败,错误为 <top (required)> 中的“block (2 levels)”

ruby-on-rails - PSQL 查询汇总 "has many through"关系上的列产生重复项

ruby-on-rails - Hstore 查询以使用 ruby​​ on rails 查找与任何数组元素匹配的记录

ios - 无法运行 Appium 服务器