Skip to content

Instantly share code, notes, and snippets.

@ismasan
Created February 25, 2009 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ismasan/70409 to your computer and use it in GitHub Desktop.
Save ismasan/70409 to your computer and use it in GitHub Desktop.
class Post < ActiveRecord::Base
belongs_to :user
belongs_to :shop
named_scope :by_author, lambda {|user_id|
return {} if user_id.blank?
{:conditions => {:user_id => user_id}}
}
named_scope :like, lambda {|q|
return {} if q.blank?
t = ActiveRecord::Base.connection.quote("%#{q}%")
{:conditions =>["title like ? OR body like ?", t, t]}
}
named_scope :by_year, lambda {|year|
return {} if year.blank?
{:conditions => ["YEAR(published_on) = ?", year]}
}
named_scope :by_month, lambda {|month|
return {} if month.blank?
{:conditions => ["MONTH(published_on) = ?", year]}
}
named_scope :recent, lambda {|limit|
{:limit => limit}
}
end
# Usage:
@posts = @shop.posts \
.by_author(params[:user_id]) \
.like(params[:q]) \
.by_year(params[:year]) \
.by_month(params[:month])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment