0

I am trying to query model table:

> 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 table contains fields sender_id, recipient_id, is_read. As the result I've got an arrays of hashes where messages_count is not present.

I tried in my

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   

also I tried to override get hash like this

  def serializable_hash(options = {})

  end

this was not triggered.

What can I try else? Thanks!

1 Answers1

0

I found the solution in 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

Returns:

[{"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"}]
Community
  • 1
  • 1