2012-03-20 52 views
0

说我有一个模型用户has_many发布子女。只在Rails中选择模型的某些孩子

user = User.first 
posts = user.posts 

,但我怎么能削减下来的职位,以满足某些条件:

很显然,我可以用这样的访问的孩子吗?

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

我on Rails的2.3.11

回答

1

Rails2:

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

Rails3中:

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

是不是post.all忽略了它只是某个用户的帖子这个事实? – you786 2012-03-20 02:20:32

+0

经过一小段改变(我将其添加到答案中)后,此功能完美无缺。谢谢! – you786 2012-03-20 03:49:59

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 
+0

这真的很有用,所以我投你一票,但它并没有直接回答我的问题。不管怎么说,多谢拉! – you786 2012-03-20 03:48:48

+0

@ yaj786,那么你的问题是什么?我以为你想以声明的方式获得最近的帖子。 – 2012-03-20 04:51:36

相关问题