code_junkie

Mixing ActiveRecord find Conditions

Nov 10th, 2011
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. Class Test < ActiveRecord::Base
  2. named_scope :created_after_2005, :conditions => "created_on > 2005-01-01"
  3. named_scope :named_fred, :conditions => { :name => "fred"}
  4. end
  5.  
  6. Test.created_after_2005.named_fred
  7.  
  8. Class Test < ActiveRecord::Base
  9. named_scope :created_after, lambda { |date| {:conditions => ["created_on > ?", date]} }
  10. named_scope :named, lambda { |name| {:conditions => {:name => name}} }
  11. end
  12.  
  13. Test.created_after(Time.now-1.year).named("fred")
  14.  
  15. Person.find(:all, :conditions => ["created_at > ? AND name IN (?)", date, names])
  16.  
  17. Person.find(:all, :conditions => ["created_at > ? AND name = ?", date, name])
  18.  
  19. class Post < ActiveRecord::Base
  20. named_scope :published, :conditions => {:status => 'published'}
  21. end
  22.  
  23. @post = Post.published
  24.  
  25. @posts = current_user.posts.published
  26.  
  27. class Person < ActiveRecord::Base
  28. named_scope :registered, lambda { |time_ago| { :conditions => ['created_at > ?', time_ago] } }
  29. named_scope :with_names, lambda { |names| { :conditions => { :names => names } } }
  30. end
  31.  
  32. names = ["dave", "jerry", "mike"]
  33. date = DateTime.now
  34. Person.find(:all, :conidtions => ["created_at > ? AND name IN ?", date, names])
Add Comment
Please, Sign In to add comment