Rails 4中使用Finder_SQL的Has_Many已过时

5

我正在将一个Rails应用程序升级到4.0版本。我收到了以下的弃用警告信息。我已经在Google上搜索过这个问题,但没有找到任何解释如何更改它的资料。

DEPRECATION WARNING: The :finder_sql association option is deprecated. Please find an alternative (such as using scopes)...

这里是导致警告的范围:
has_many :elective_instructors,
       :class_name => "Instructor",
       :finder_sql => proc { "SELECT DISTINCT people.* FROM people
                       INNER JOIN class_sections ON class_sections.instructor_id = people.id
                       INNER JOIN courses ON courses.id = class_sections.course_id
                       INNER JOIN taken_classes ON class_sections.id = taken_classes.class_section_id
                       WHERE 
                       courses.core = FALSE
                       AND
                       taken_classes.student_id = #{id}
                       AND
                       people.type = 'Instructor'
                       AND
                       people.ignore = FALSE" }

非常感谢您的帮助和建议!如果您有任何好的想法,欢迎分享。谢谢!

1个回答

3
截止至4.1版本,:finder_sql不仅已被弃用 - 它已被完全从Rails中删除
以下是一种通过使用作用域来实现类似功能的方法。假设我们有一个用户类和一个工作类(因此一个用户可以拥有许多工作)。并且假设我们想要查找该用户持有的所有不同的工作(虽然是人为的例子,但它阐明了这一点),并且假设我们想要为此使用自定义SQL。我们可以使用find_by_sql如下所示。
class Job < ActiveRecord::Base
  scope :distinct_user_jobs, -> (user_id){ find_by_sql(["SELECT DISTINCT jobs.* FROM jobs WHERE jobs.user_id=?", user_id]) }
end

然后传入user_id

user = User.first
Job.distinct_user_jobs(user.id)

2
谢谢,但是我该如何更改has_many关系调用以使用作用域?将作用域链接到has_many行吗? - John Cowan
我不相信你可以只是“将作用域链接到has_many”。事实上,如果你仔细看我的例子——作用域在MANY模型上,而不是反过来。在你的情况下,作用域必须在Instructor模型上设置。 - Kalman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接