在多个表的连接与使用ActiveRecord的命名范围 [英] Joins across multiple tables with ActiveRecord with named scopes

查看:98
本文介绍了在多个表的连接与使用ActiveRecord的命名范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我爱拍命名范围钢轨。然而,我遇到了有点咸菜。 香港专业教育学院得到了pretty的舒适使用命名范围的连接,像这样:

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'"

现在pretend我有一个表叫巴兹这是包含在酒吧表的外键。我需要的是这样的:

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?

感谢

推荐答案

您也不会太远了。这应该为你工作:

You are not that far off. This should work for you:

named_scope: foo, :joins => {:bar => :baz}, :conditions => "bazes.your_attr = 'something_else'"

这假定巴兹的复数是bazes。不需要指定联接bar.id到bazes.bar_id的条件下,它会从推断:联接

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.

这篇关于在多个表的连接与使用ActiveRecord的命名范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆