通过Rails中的belongs_to的关系查询记录

问题描述:

我有一个活动的模式,他们belong_to一个位置

I have an Activities model, and they belong_to a Location

我该如何选择,其location.country =澳大利亚所有的活动? (例如)

How do i select all the activities whose location.country = Australia? (for example)

我可以做这样的范围之内?

Can I do this within a scope?

你所谈论的是一个连接的一种查询。您可以尝试在控制台中像这样的查询,如:

The kind of query you're talking about is a join. You can try queries like this in the console like:

Activity.joins(:locations).where('locations.country = "Australia"')

这意味着,SQL是要采取一切与当时有关的活动和地点,找到地点,其中国家=澳大利亚,然后返回你与那些位置相关的活动。

This means that SQL is going to take all the activities and locations associated with then, find the locations where country=Australia, and then return you the activities that are associated with those locations.

要使它成为一个更可重复使用的范围,对全国的变量在模型中定义的:

To make this into a more reusable scope, define it on your model with a variable for country:

scope :in_country, lambda {|country| joins(:locations).where('locations.country = ?',country)}

您可以了解更多有关这方面的 API文档

You can learn more about this in the API docs.