Ruby on rails 在Rails中仅选择模型的某些子级

Ruby on rails 在Rails中仅选择模型的某些子级,ruby-on-rails,model,find,selection,finder,Ruby On Rails,Model,Find,Selection,Finder,假设我有一个模型用户,他有很多Post子用户 很明显,我可以通过以下方式访问孩子们: 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上,Rails 2: recent_pos

假设我有一个模型用户,他有很多Post子用户

很明显,我可以通过以下方式访问孩子们:

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上,Rails 2:

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

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

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

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

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
试试这个:

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

所有人都忽略了一个事实,那就是它只是某个用户的帖子?在做了一个小改动(我在答案中添加了这个改动)之后,这个功能运行得非常好。谢谢所有人都忽略了一个事实,那就是它只是某个用户的帖子?在做了一个小改动(我在答案中添加了这个改动)之后,这个功能运行得非常好。谢谢知道这一点真的很有用,所以我投票支持你,但它没有直接回答我的问题。无论如何谢谢你@yaj786,那你的问题是什么?我以为你想以声明的方式获得最近的帖子。这很有用,所以我投票支持你,但它没有直接回答我的问题。无论如何谢谢你@yaj786,那你的问题是什么?我以为你想以声明的方式获得最近的帖子。