nobilik nobilik - 4 years ago 115
Ruby Question

How to associate many users with one message at once?

I have posts that associated with many users. When somebody comment one of them, my app creates a message that should be delivered to users associated with post. I want to associate all commented post users with new message. How to do it at once, without iterator?

users.each do |user|
user.messages << message
end

Answer Source

AFAIK, this is not achievable with standard rails syntax, but you are still free to use plain old good SQL:

ActiveRecord::Base.connection.execute %Q{
  UPDATE users
  SET message_id = #{message.id}
  WHERE post_id = #{post.id}
}

The query above is likely not precisely correct, since you did not provide the relationship model, but I guess you get the point.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download