2011-08-11 54 views
0

这在目前的状态下工作,但感觉马虎。如何在特定日期后查询所有记录?

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

任何人都可以提出一个不同的方式,我可以写这个查询吗?我需要返回08/11/2011之后创建的所有评论的计数。

编辑: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) 
相关问题