【问题标题】:Has_Many :Through or :finder_sqlHas_Many :Through 或 :finder_sql
【发布时间】: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


    【解决方案1】:

    如果你这样做了会怎样

    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}" }
    

    【讨论】:

    • 女士和细菌,赢家。这里的文档是错误的,你不要在 :finder_sql 上做一个 :conditions,你只是在里面构建它。
    【解决方案2】:

    其实我会这样写:

    has_many :offsprings, :finder_sql => proc {OFFSPRING_SQL % {id: id}}
    
    OFFSPRING_SQL = "SELECT DISTINCT offsprings.*
                       FROM humans offsprings
                      INNER JOIN relationships r
                            ON r.human_id = offsprings_id
                            WHERE r.source_human_id = %{id}"
    

    我认为它使关联更易于理解,并且使裸 SQL 更易于编辑。它还利用了基于字符串的参数插值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-04
      • 2016-01-20
      • 2014-09-01
      • 2011-03-12
      • 1970-01-01
      相关资源
      最近更新 更多