2012-03-20 18 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)) 

私は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

+0

小さな変更(これを私が答えに加えた)の後、これは完全に機能しました。ありがとう! – you786

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

+0

@ yaj786、あなたの質問は何でしたか?最近の投稿を宣言的に入手したいと思っていました。 –

関連する問題