使用具有命名范围的 ActiveRecord 跨多个表进行联接
我喜欢为 Rails 制作命名范围。 然而,我遇到了一些麻烦。 我已经非常习惯使用命名范围进行连接,如下所示:
named_scope :foo, :joins => :bar, :conditions => "bar_attribute = 'something'"
现在假设我有一个名为 baz 的表,其中包含 bar 表中的外键。 我需要这样的东西:
named_scope :foo, :joins => (:bar => :baz), :conditions => "bar.id = baz.bar_id AND baz_attribute = 'something_else'"
这怎么可能?
谢谢
I love making named scopes for rails. however, I ran into somewhat of a pickle.
Ive gotten pretty comfortable using named scopes for joins like so:
named_scope :foo, :joins => :bar, :conditions => "bar_attribute = 'something'"
Now pretend I have a table called baz which is contains a foreign key from the bar table. I need something like this:
named_scope :foo, :joins => (:bar => :baz), :conditions => "bar.id = baz.bar_id AND baz_attribute = 'something_else'"
How possible is this?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你离我们并不遥远。 这应该对你有用:
这假设 baz 的复数是 bazes。 您不需要指定连接 bar.id 和 bazes.bar_id 的条件,它将从 :joins 推断出来。
You are not that far off. This should work for you:
This assumes that the plural of baz is bazes. You don't need to specify the condition that joins bar.id to bazes.bar_id, it will be inferred from :joins.
也许你可以结合
has_many :through => 来做到这一点 ...
关系。Maybe you can do this in combination with a
has_many :through => ...
relation.