开发者

What is Rails ActiveRecord find(x) method that is equivalent to a lazy-evaluated-scope? How to refactor ActiveRecord finder?

开发者 https://www.devze.com 2023-03-08 05:57 出处:网络
Is Rails\' find(x) method on a model lazy? If not, what is the equivalent? I am new to Rails, so I found myself writing scopes like this:

Is Rails' find(x) method on a model lazy? If not, what is the equivalent?

I am new to Rails, so I found myself writing scopes like this:

class Course < ActiveRecord::Base
  scope :by_instructor_id, lambda { |instructor_id| where(:instructor_id => instructor_id) }
  scope :by_course_template_id, lambda { |course_template_id| where(:course_template_id => course_template_id ) }
  scope :by_company_id, lambda { |company_id| joins(:instructor).merge(CompanyUser.by_company_id(company_id)) }
end

It's not a lot of work, but now I'm asking myself... if Rails provided these with a scope, I wouldn't have to write them.

So, does Rails offer them? Can I do something like the below code and only make it do 1 database call?

Company.find(params[:id]).instructors.courses

instead of

Course.by_company_id(params[:id])

Which is correct? I know Course.by_company_id(params[:id]) is only 1 database call. It is very familiar to writing SQL or queries in Hibernate. But if you can write it the other way, maybe one should?

However, I don't want to write Company.find(params[:id]).instructors.courses if it results in more than 1 database call. I can see the advantage though because it means never having to write the 3 scopes I sh开发者_运维百科owed you above, but I am worried that Company.find(x) is not lazy. Is it?


Try using #scoped method on a model before calling #find:

user = User.scoped.instructors.courses.find(params[:id])


To make find by id query lazy you can add new method to your controller and then add this method as helper.

# company
def company  
  @company ||= Company.find(params[:id])  
end  
helper :company

#view
<%= company.name %>

To get more information you can check great RailsCast - Decent Exposure

0

精彩评论

暂无评论...
验证码 换一张
取 消