开发者

Rails 3 getting wrong count in query

I'm trying to get the number of messages that haven't been read.

The Message model has a column called read_at. If the message has been read there is a value in read_at, if it's unread then that value is nil.

I have one read message and one unread message. I get 0 unread messages (I should be getting 1). This is the code:

Message.all(:conditions => 
  ['website_id = ? AND read_at = ?', current_website.id, nil]).count

It seems that the query is right, since the development log is showing me

Message Load (0.2ms)  SELECT "messages".* FROM "messages" 
                        WHERE (we开发者_JAVA百科bsite_id = 2 AND read_at = NULL)


instead of read_at = NULL try read_at is null, it is a SQL thing.

:conditions => ['website_id = ? AND read_at is ?', current_website.id, nil]

Here is a short article on SQL nulls, and how to use them:

http://www.w3schools.com/sql/sql_null_values.asp

Hope it helps



Though the problem is the one pointed by @pdjota, you should use Rails 3 notation, here is how I would write it:

Message.where('website_id = ? AND read_at IS NULL', current_website.id).count
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜