【发布时间】:2012-12-16 11:17:10
【问题描述】:
我有一个活动模型,它们属于一个位置
如何选择所有 location.country = 澳大利亚的活动? (例如)
我可以在一个范围内这样做吗?
【问题讨论】:
标签: ruby-on-rails ruby activerecord relation
我有一个活动模型,它们属于一个位置
如何选择所有 location.country = 澳大利亚的活动? (例如)
我可以在一个范围内这样做吗?
【问题讨论】:
标签: ruby-on-rails ruby activerecord relation
使用最新的 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')
【讨论】:
您所说的查询类型是联接。您可以在控制台中尝试这样的查询:
Activity.joins(:locations).where('locations.country = "Australia"')
这意味着 SQL 将获取与 then 相关联的所有活动和位置,找到 country=Australia 的位置,然后返回与这些位置相关联的活动。
要使其成为更可重用的范围,请在您的模型上使用国家/地区变量定义它:
scope :in_country, lambda {|country| joins(:locations).where('locations.country = ?',country)}
您可以在API docs 中了解更多信息。
【讨论】:
:location 是复数,而且这种关系似乎不存在