让一个问题总是:包括它的作者,如何?
class Question < ActiveRecord::Base
belongs_to :author
end
class Author < ActiveRecord::Base
has_many :questions
end
当我发现一些问题时,我通常需要同时得到他们的作者,所以我使用:
Question.find(:all, :include=>:authors)
但我不会到处写“:include”部分。我希望我只能在某个地方定义一次“包含”,当我发现问题时,作者将被自动加载。有什么办法可以做到这一点吗?
class Question < ActiveRecord::Base
belongs_to :author
end
class Author < ActiveRecord::Base
has_many :questions
end
When I find some questions, I usually need to get their authors at the same time, so I use:
Question.find(:all, :include=>:authors)
But I don't write the ":include" part everywhere. I hope I can define the "include" somewhere only once, and when I find questions, the author will be automaticly loaded. Is there any way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用default_scope。有关详细信息,请参阅此处: http://api.rubyonrails.org/classes/ActiveRecord /Base.html#M002313
You can use default_scope. See here for details: http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002313
我更喜欢这样使用:
I prefer to use like this: