The DB relation in rails models:
Class User < ActiveRecord::Base
has_many :user_messages
has_many :messages
end
Class UserMessage < ActiveRecord::Base
belongs_to :user
belongs_to :message
end
Class Message < ActiveRecord::Base
belongs_to :user
has_many :user_messages
end
I want to optimize the following code:
ids.each do |id|
user = User.find_by_id(id)
unread_count = user.user_messages.where(:folder => user.inbox_id, :read => false).count
puts "UserID #{id} ---- Unread Message count #{unread_count}"
end
Can some tell me how can I optimize the above code using Active record or SQL Query. I basically want to reduce DB queries and time the above code take to complete the loop.
Thanks in advance.
unread_countcolumn inuserstable to storeunread_countfor each user.