如何在特定日期之后查询所有记录?

时间:2011-08-11 20:10:08

标签: mysql ruby-on-rails activerecord coding-style

这在当前状态下有效,但感觉很草率。

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

任何人都可以提出一种不同的方式来编写此查询吗?我需要返回2011年11月11日之后创建的所有评论的计数。

编辑:Rails 2.3.9

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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

然后你的查询将是:

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