My question is:
is there some most efficient solution for this code in ruby on rails and mongoid odm?
messages_without_responses = Message.all.select{|message| message.sender == current_user || message.receiver == current_user}
messages = Array.new
messages_without_responses.each do |m|
if m.message_responses.count > 0
messages << m
else
messages << m if m.receiver_id == current_user.id && m.place_receiver == "inbox"
end
end
Thank you very much!
I don’t know how many records are in your DB, but if the number might get large, you are better filtering out the records you want at the DB level rather than in Ruby. Hence the SQL conditions on
Message.all(you’ll have to translate as necessary to make this usable with Mongoid; I’ve never used it before).The rest is not bad, but you could make it more concise: