Question

How can i parse my json style result from Cassandra? I'm using the cassandra-cql gem for rails and i want to parse the query result to list all messages. My query looks like:

def self.get_messages uid
  @@db.execute("SELECT * FROM messages WHERE uid=?", uid)
end

how can i list all messages? My current view is:

<% json_dec = ActiveSupport::JSON.decode(u.row.to_json) %>
<% json_dec.each do |f| %>
  <%= f[1] %><br/>
<%end%>

and it returns:

1
[{"name"=>"uid", "value"=>"1", "timestamp"=>-1}, {"name"=>"1326751801", "value"=>"test content", "timestamp"=>1326751801970000}, {"name"=>"1326754147", "value"=>"some content to test", "timestamp"=>1326754147612000}]

Is there any better way for the query? how do others solve this problem?

Was it helpful?

Solution

Encoding to json and the decoding again doesn't make much sense. Instead you can call #to_hash on the row object which will give you a hash of column_name => value. Then you could iterate over that:

<% row.to_hash.each do |key, value| %>
  <p>key: <%= key %>, value: <%= value %></p>
<%end%>

It also looks like you need to change your implementation of get_message to call fetch:

def self.get_messages uid
  @@db.execute("SELECT * FROM messages WHERE uid=?", uid).fetch
end 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top