Swartz
Swartz

Reputation: 1091

Rails: any way to preload (include) parent association

I have a Rails 2.3 app with the following models.

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


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

Whenever I query MessageCopy, I always need to reference parent message's attributes. So I always end up pre-loading (via :include => :message) to reduce # of db queries.

So far I came up with this:

named_scope :with_parent_msg, :include => :message

This allows me easily to do this:

@user.message_copies.with_parent_msg

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

Open to any suggestions. Thanks!

Upvotes: 3

Views: 2918

Answers (1)

Dogbert
Dogbert

Reputation: 222108

You can define a default_scope for this

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

Upvotes: 4

Related Questions