rails ActiveModel添加不持久的属性

时间:2015-09-02 15:18:25

标签: sql ruby-on-rails activerecord serialization find-by-sql

我正在尝试查询模型表:

> 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")

数据库表包含字段sender_id,recipient_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

没有触发。

我可以尝试其他什么?谢谢!

1 个答案:

答案 0 :(得分:0)

我找到了解决方案 this thread

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"}]