让ActiveRecord自动附加一些SQL

发布于 2024-11-19 05:53:15 字数 609 浏览 5 评论 0原文

[更新问题以澄清]

我可以在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

薄荷港 2024-11-26 05:53:15

查看有关使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文