Has_Many :Through or :finder_sql

▼魔方 西西 提交于 2019-12-05 02:52:00

What if you do

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

Actually, I'd write it this way:

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

I think it makes the association easier to understand, and it make the naked SQL easier to edit. It also takes advantage of string-based parameter interpolation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!