Rails: any way to preset (enable) parent association

I have a Rails 2.3 application with the following models.

class Message << AR::Base
  has_many :message_copies
end


class MessageCopy << AR::Base
  belongs_to :message
end

Whenever I request MessageCopy, I always need to refer to the attributes of the parent messages. So I always get preload (via: include =>: message) to reduce the number of db requests.

So far I have come up with this:

named_scope :with_parent_msg, :include => :message

This allows me to easily do this:

@user.message_copies.with_parent_msg

Is there a better way to do this? So I don’t need to always call with_parent_msg?

Open all offers. Thank!

+3
source share
1 answer

You can define default_scope for this

class MessageCopy << AR::Base
  belongs_to :message
  default_scope include(:message)
end
+3
source

Source: https://habr.com/ru/post/1793174/


All Articles