2

I have a model Messages w the fields: id, message, read, view_count. View count is calculated from another table, it's not in the message model

What I want to do is loop over all the Messages and track all unreads (read = false) and the view count per the unreads to output something like this:

1, "message stuff", false, 14
2, "message stuff", false, 31
3, "message stuff", false, 1

While looping through messages like so:

Messages.each do |m|
end

In the loop, how can I build an array that captures the message.id and the view_count. And then how can I output the final result?

Thank you

3
  • what are u rolling this up to a user? Commented Mar 14, 2013 at 3:10
  • you said view_count is calculated from another table, is this column only a counter_cache? or do you also need to calculate this inside the block? Commented Mar 14, 2013 at 3:11
  • yeah is there a relationship between the two? like Messages.views? Commented Mar 14, 2013 at 3:11

3 Answers 3

3
mes_fields = Array.new
messages = Array.new
mess = Messages.where("read = ?", false)


mess.each_with_index do |m_row, index|
    m_row.each do |m|
        mes_fields.push(m)
    end
    messages.push(mes_fields[index])
end

Then message would look like

[[1, "message stuff", false, 14],
 [2, "message stuff", false, 31],
 [3, "message stuff", false, 1]]
Sign up to request clarification or add additional context in comments.

Comments

3

can i recommend a hash instead?

message_hash = {}

Messages.where(:read => false).each do |m|
  messages_hash[m.id] = m.view_count
end

puts messages_hash

assuming

class Messages
  def view_count
    #some view_count calculation code.
  end
end

untested but that should be close.

outputs

{
  11 => 33,
  12 => 11,
  13 => 34,
}

2 Comments

hmm this doesn't make any sense. m.id will be unique so the hash will always have values = 1. am i missing something?
the question was vague in that regaurd, we talk about a rollup on read count but i dont know what we've rolling up to?
0

Try this:

Message.where(:read => false).map{ |m| [m.id, m.view_count]}
# => [ [ 1, 14], [ 2, 31], [ 3, 1]]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.