让ActiveRecord自动附加一些SQL
[更新问题以澄清]
我可以在 Rails 3/3.1 中创建一个模型并使 ActiveRecord 自动使用/附加我配置到该模型的一些联接吗?
例如:
使用这样的代码:
class Component < ActiveRecord::Base
def self.base_query
joins("join t05 on d04.t05_ukey = t05.ukey left join d03 on d04.d03_ukey = d03.ukey left join d16 on d04.d16_ukey = d16.ukey")
end
end
Component.first # under the hood is doing Component.base_query.first
Component.where(...) # under the hood is doing Component.base_query.where
但是 ActiveRecord 在底层调用方法 base_query 而无需显式调用它。只是为了让它更像 Rails。
有什么想法吗?
[updating question to clarify]
Can I create a model in Rails 3/3.1 and make ActiveRecord automatically use/append some joins I configured to that model?
Ex:
Use code like this:
class Component < ActiveRecord::Base
def self.base_query
joins("join t05 on d04.t05_ukey = t05.ukey left join d03 on d04.d03_ukey = d03.ukey left join d16 on d04.d16_ukey = d16.ukey")
end
end
Component.first # under the hood is doing Component.base_query.first
Component.where(...) # under the hood is doing Component.base_query.where
But ActiveRecord calls the method base_query under the hood without the need to explicitly call it. Just to make it more Rails-like.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
查看有关使用 Arel 进行活动记录查询的指南。关于这个主题还有一些非常好的railscasts (@railscasts.com)。如果您发现自己有丑陋的 where 子句等,请看一下 meta_where gem。我以这三件事发誓。
Take a look at this guide about active record querying with Arel. There are a couple of really good railscasts (@railscasts.com) on the topic as well. And if you find yourself with ugly where clauses, etc, take a peek at the meta_where gem. I swear by these three things.