Rails 2.3.x - 惰性数据库查询
我想基于 GET 参数并使用 named_scope
在 ActiveRecord 中构造一个查询。我想我应该链接一些范围并根据 GET 参数可用性添加条件,但我担心这会使数据库过度工作,在添加的每个查询部分上发送一个新查询:
# in model
named_scope :sorted, :order => 'title, author'
named_scope :archived, :conditions => { :is_archived => true }
named_scope :by_date, lambda { |date| { :conditions => [ 'updated_at = ?', date ] } }
# in controller / helper
@articles = Article.sorted.all
@articles = @articles.by_date(params[:date]) if params[:date]
@articles = @articles.archived if params[:archived] == '1'
我想到的另一个选项是构建一个方法链接字符串然后将使用Object#send
发送到对象,但是当named_scope接收参数(例如by_date
)时,这似乎有点脏并且有些问题。我意识到我可以构造一个查询字符串以与 :conditions => 一起使用...
在ActiveRecord::Base#find
中,但我想我应该首先尝试使用named_scope 来看看是否可以使用后者进行延迟查询。关于如何使用named_scope来做到这一点并且不让数据库被查询轰炸有什么建议吗?谢谢。
I would like to construct a query in ActiveRecord based on GET params and using named_scope
. I thought I'd chain some scopes and add conditions based on GET param availability, but I fear this will overwork the db, sending a new query on each query portion added:
# in model
named_scope :sorted, :order => 'title, author'
named_scope :archived, :conditions => { :is_archived => true }
named_scope :by_date, lambda { |date| { :conditions => [ 'updated_at = ?', date ] } }
# in controller / helper
@articles = Article.sorted.all
@articles = @articles.by_date(params[:date]) if params[:date]
@articles = @articles.archived if params[:archived] == '1'
Another option I've thought of is building a method chaining string that'll then be sent to the object using Object#send
, but that seems a bit dirty and somewhat problematic when the named_scope receives arguments (like by_date
). I realize I can construct a query string to use with :conditions => ...
in ActiveRecord::Base#find
, but I thought I'd try first with named_scope to see if it's possible to do lazy querying with the latter. Any suggestions on how to do this using the named_scope and not having the database bombarded by queries? thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你可以让 lambda 更智能
You can make lambda more smarter