简体   繁体   中英

Eager loading for has_many associations (Rails)

Let's say I have Conversation has_many Messages :

class Conversation < ActiveRecord::Base
  has_many :messages, dependent: :destroy

  def messages_for(u)
    messages.map do |msg|
      if msg.user == u
        msg if msg.attr1.nil?
      else
        msg if msg.attr2.nil?
      end
    end
  end
end

And messages.rb:

class Message < ActiveRecord::Base
  belongs_to :conversation
end

As you can tell, messages_for is far from being optimal performance wise. What is the best way to eager load the associated messages as at the moment I'm getting a query every time I iterate through the messages.

Please note that I'm using Rails 3.2.22 and I tried to use something like self.includes(:messages) and joint(:messages) with no luck so far.

Assuming that I don't want to use query directly and I do want to iterate through the objects.

Any help would be appreciated.

Users are also a model and you generate N+1 in this method because for each message you pull the user so eager load it thats the best you can do.

self.includes(messages: :users).messages.map |msg|
  // rest of the code
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM