2011-08-11 8 views
0

これは現在の状態では動作しますが、お粗末です。特定の日付の後にすべてのレコードを照会する方法はありますか?

t = Time.local(2011, 8, 11) 
comments_count = Comment.count(:conditions => ["comments.user_id = (?) AND comments.created_at > (?)" , record.user_id, t]) 

誰でもこのクエリを書くことができる別の方法を提案できますか?私は2011年8月11日以降に作成されたすべてのコメントの数を返す必要があります。

EDIT:Railsの2.3.9

+0

これは何も問題ありません。トーキングレール2? 3の場合、構文をかなり上手くいくことができます。 – numbers1311407

答えて

0

をあなたはnamed_scopesを使用してコードをクリーンアップすることができます:

class Comment 
    named_scope :for_user, lambda { |user_id| 
    :conditions => ["comments.user_id = (?)", user_id] 
    } 
    named_scope :created_after, lambda { |time| 
    :conditions => ["comments.created_at > (?)", time] 
    } 

    # ... rest of class ... 
end 

aあなたのクエリは次のようになります:

t = Time.local(2011, 8, 11) 
comments_count = Comment.for_user(record.user_id).created_after(t).count() 
0

あなたは常にそれのための命名スコープ記述することができます。その後、

named_scope :created_after, lambda {|time| { :conditions => ['created_at > ?', time] } } 
named_scope :by_user, lambda {|user| { :conditions => ['user_id = ?', user.to_param] } } 

を:

Comment.created_after(some_time).by_user(some_user) 
関連する問題