ismasan (owner)

Revisions

gist: 70409 Download_button fork
public
Public Clone URL: git://gist.github.com/70409.git
Embed All Files: show embed
ActiveRecord useful named_scopes #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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])