Rails 4 Has_Many with Finder_SQL 已弃用

Joh*_*wan 5 ruby-on-rails-4

我正在将 Rails 应用程序升级到 4.0。我收到以下弃用警告。我已经谷歌了这个,但没有找到任何告诉如何改变这一点的东西。

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

这是导致警告的范围:

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" }
Run Code Online (Sandbox Code Playgroud)

任何想法将不胜感激。谢谢!

Kal*_*man 4

从 4.1 开始,:finder_sql它不仅被弃用 - 它已从Rails 中完全删除

这是通过使用范围来执行类似操作的一种方法。假设我们有一个 User 类和 Job 类(因此一个用户可以有很多工作)。假设我们想要找到该用户所从事的所有不同的工作(这是人为的示例,但它说明了这一点),并且假设我们想要为此使用自定义 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
Run Code Online (Sandbox Code Playgroud)

然后传入user_id

user = User.first
Job.distinct_user_jobs(user.id)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,但是如何更改 has_many 关系调用以使用范围?将作用域链接到 has_many 行? (2认同)