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

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

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

我可以在范围内执行此操作吗?

你正在谈论的那种查询是一种联接。 您可以在控制台中尝试这样的查询,例如:

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

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

要使其成为更可重用的范围,请在模型上使用国家/地区的变量对其进行定义:

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

您可以在API文档中了解有关此内容的更多信息。

使用最新的rails版本,您可以:

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

谨防:

  • 它是joins(:location)位置( 单数 ),因为它是belongs_to关系
  • 它是where(…)位置( 复数 ),因为它是表名

后者意味着如果您有以下内容:

 belongs_to :location, class_name: "PublicLocation" 

查询将是:

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

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

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