Rails 4 Has_Many with Finder_SQL 已弃用 [英] Rails 4 Has_Many With Finder_SQL Deprecated
问题描述
我正在将 Rails 应用升级到 4.0.我收到以下弃用警告.我已经谷歌了这个,但没有找到任何告诉如何改变这一点的信息.
I am upgrading a Rails app to 4.0. I am receiving the following deprecation warning. I have Google'd on this, but have not found anything that tells how to change this.
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" }
任何想法将不胜感激.谢谢!
Any ideas would be greatly appreciated. Thanks!
推荐答案
从 4.1 开始,:finder_sql
不仅被弃用 - 它已经被 完全从 Rails 中删除.
As of 4.1, :finder_sql
is not just deprecated - it has been completely REMOVED from Rails.
这是通过使用范围来做类似事情的一种方法.假设我们有一个 User 类和 Job 类(所以一个用户可以有很多工作).假设我们想要找到该用户拥有的所有不同的作业(人为的例子,但它说明了这一点),并且假设我们想要为此使用自定义 SQL.我们可以使用 find_by_sql 如下
Here is one way to do something similar through the use of scopes. Let's say we have a User class and Job class (so a user can have many jobs). And let's say that we want to find all distinct jobs that this user holds (contrived example, but it illustrates the point) and let's say we want to use custom SQL for this. We can use find_by_sql as follows
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)
这篇关于Rails 4 Has_Many with Finder_SQL 已弃用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!