class Question < ActiveRecord::Base
   belongs_to :author
end

class Author < ActiveRecord::Base
   has_many :questions
end

当我发现了一些问题,我通常需要在同一时间得到他们的作家,所以我用:

Question.find(:all, :include=>:authors)

但我不写的:无处不在的部分“包括”。我希望我可以定义“包括”的地方只有一次,当我发现的问题,笔者将全自动加载。有没有办法做到这一点?

有帮助吗?

解决方案

可以使用default_scope。看到这里的细节: http://api.rubyonrails.org/classes/ActiveRecord /Base.html#M002313

其他提示

我更喜欢使用这样的:

has_many :questions, :include=>:author
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top