Ruby-on-rails 在Rails中通过它的belongs_to关系查询记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14116122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:15:02  来源:igfitidea点击:

Query records through its belongs_to relation in Rails

ruby-on-railsrubyactiverecordrelation

提问by Will

I have an Activities model, and they belong_to a Location

我有一个活动模型,它们属于一个位置

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

如何选择 location.country = Australia 的所有活动?(例如)

Can I do this within a scope?

我可以在一个范围内做到这一点吗?

回答by Nycen

With the latest rails versions you can do:

使用最新的 rails 版本,您可以执行以下操作:

Activity.joins(:location).where(locations: { country: "Australia" })

Beware:

谨防:

  • it is location (singular) in joins(:location)because it's a belongs_to relationship
  • it is locations (plural) in where(…)because it's the table name
  • 它是位置(单数joins(:location)因为它是一个belongs_to关系
  • 它是位置(复数),where(…)因为它是表名

The latter means that if you had the following:

后者意味着,如果你有以下几点:

belongs_to :location, class_name: "PublicLocation"

the query would be:

查询将是:

 Activity.joins(:location).where(public_locations: { country: "Australia" })

回答by Andrew

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

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.

这意味着 SQL 将获取与 then 关联的所有活动和位置,找到 country=Australia 的位置,然后返回与这些位置关联的活动。

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)}

You can learn more about this in the API docs.

您可以在API 文档 中了解更多相关信息。

回答by Dave S.

Yes, a scope can be used. Something like this ought to work on the Activities model:

是的,可以使用范围。像这样的事情应该适用于活动模型:

scope :down_under, 
    joins(:locations).
    where("locations.country = 'Australia')