Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 Has_Many With Finder_SQL Deprecated

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)...

Here is the scope that is causing the warning:

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!

like image 352
John Cowan Avatar asked Oct 18 '22 22:10

John Cowan


1 Answers

As of 4.1, :finder_sql is not just deprecated - it has been completely REMOVED from Rails.

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

And then pass in the user_id

user = User.first
Job.distinct_user_jobs(user.id)
like image 107
Kalman Avatar answered Oct 21 '22 09:10

Kalman