开发者

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 hav开发者_运维问答e to always call with_parent_msg?

Open to any suggestions. Thanks!


You can define a default_scope for this

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜