0

我正在尝试查询模型表:

> messages = Message.find_by_sql("select count(*) as messages_count,
> sender_id, recipient_id, min(is_read) as is_read from messages group
> by sender_id, recipient_id")

DB 表包含字段 sender_id、receiver_id、is_read。结果,我得到了一个不存在messages_count 的哈希数组。

我试过在我的

class Message < ActiveRecord::Base
  def attributes
    super.merge('messages_count' => self.messages_count)
  end

  after_initialize do
    self.messages_count = nil unless @attributes.key?("messages_count")
  end   

我也尝试像这样覆盖get hash

  def serializable_hash(options = {})

  end

这没有被触发。

我还能尝试什么?谢谢!

4

1 回答 1

0

我在 这个线程中找到了解决方案。

messages = ActiveRecord::Base.connection
                 .select_all("select count(*) as messages_count,
                           sender_id, recipient_id, min(is_read) as is_read
                           from messages group by sender_id, recipient_id").to_a

回报:

[{"messages_count"=>3, "sender_id"=>409608538, "recipient_id"=>762146111, "is_read"=>"f"}, {"messages_count"=>1, "sender_id"=>409608538, "recipient_id"=>950961012, "is_read"=>"f"},
 {"messages_count"=>2, "sender_id"=>762146111, "recipient_id"=>409608538, "is_read"=>"t"}]
于 2015-09-02T18:32:36.103 回答