在Rails中只选择某些模型的子项

时间:2012-03-20 02:10:42

标签: ruby-on-rails model find selection finder

假设我有一个模型用户has_many Post children。

显然我可以使用以下内容访问孩子:

user = User.first
posts = user.posts

但是我怎样才能将这些帖子削减到那些符合某些条件的帖子?

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

我正在使用Rails 2.3.11

2 个答案:

答案 0 :(得分:2)

试试这个:

class User
  has_many :posts do
    def recent duration=1.day
      all(:conditions => ["created_at >= ? ", duration.ago])
    end
  end

end

现在您可以进行以下调用:

user.posts # all posts for user
user.posts.recent # posts since last one day
user.posts.recent(2.days) # posts since last two days
user.posts.recent(30.minutes) # posts since last 30 minutes

答案 1 :(得分:1)

Rails 2:

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

Rails 3:

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