什么是相当于惰性求值范围的 Rails ActiveRecord find(x) 方法?如何重构ActiveRecord finder?
Rails 模型上的 find(x) 方法是懒惰的吗?如果不是,相当于什么?
我是 Rails 的新手,所以我发现自己正在编写这样的作用域:
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
这并不是很多工作,但现在我问自己...如果 Rails 为这些提供了作用域,我就不必编写它们了。
那么,Rails 提供它们吗?我可以执行类似以下代码的操作并仅使其执行 1 次数据库调用吗?
Company.find(params[:id]).instructors.courses
而不是
Course.by_company_id(params[:id])
哪个是正确的?我知道 Course.by_company_id(params[:id])
只是 1 个数据库调用。在 Hibernate 中编写 SQL 或查询非常熟悉。但如果你可以用另一种方式写,也许应该?
但是,如果导致超过 1 个数据库调用,我不想编写 Company.find(params[:id]).instructors.courses
。我可以看到其中的优势,因为这意味着永远不必编写上面向您展示的 3 个作用域,但我担心 Company.find(x)
并不懒惰。是吗?
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 showed you above, but I am worried that Company.find(x)
is not lazy. Is it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在调用
#find
之前尝试在模型上使用#scoped
方法:Try using
#scoped
method on a model before calling#find
:要使
find
by id 查询变得惰性,您可以向控制器添加新方法,然后将此方法添加为帮助程序。要获取更多信息,您可以查看精彩的 RailsCast - Decent Exposure
To make
find
by id query lazy you can add new method to your controller and then add this method as helper.To get more information you can check great RailsCast - Decent Exposure