sa125
sa125

Reputation: 28971

Rails 2.3.x - lazy db querying

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.

Upvotes: 0

Views: 307

Answers (1)

Sector
Sector

Reputation: 1210

You can make lambda more smarter

# in model
named_scope :sorted, :order => 'title, author'
named_scope :archived, lambda { |is_archived| (is_archived == 1) ? {:conditions => {:is_archived => true}} : {}}
named_scope :by_date, lambda { |date| date.nil? ? {} : { :conditions => [ 'updated_at = ?', date ]}}

# in controller / helper
@articles = Article.by_date(params[:date]).archived(params[:archived]).sorted

Upvotes: 1

Related Questions