Search code examples
ruby-on-railsmodelfindselectionfinder

Choosing only certain children of models in Rails


Say I have a model User which has_many Post children.

Obviously I can access the children using something like this:

user = User.first
posts = user.posts

but how can I pare down those posts to those that meet certain conditions?

user = User.first
posts = user.posts
recent_posts = posts.where(:created_at => > (Time.now - 1.day))

I'm on Rails 2.3.11


Solution

  • Rails2:

    recent_posts = posts.all(:conditions=> ['created_at > ?', (Time.now - 1.day)])
    

    Rails3:

    recent_posts = posts.where('created_at > ?', (Time.now - 1.day))