在Rails中通过它的belongs_to关系查询记录 [英] Query records through its belongs_to relation in Rails
本文介绍了在Rails中通过它的belongs_to关系查询记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个活动模型,它们属于一个位置
I have an Activities model, and they belong_to a Location
如何选择 location.country = Australia 的所有活动?(例如)
How do i select all the activities whose location.country = Australia? (for example)
我可以在一个范围内做到这一点吗?
Can I do this within a scope?
推荐答案
使用最新的 rails 版本,您可以:
With the latest rails versions you can do:
Activity.joins(:location).where(locations: { country: "Australia" })
当心:
- 它是
joins(:location)
中的位置(单数),因为它引用了belongs_to
关系名称 - 它是
where(…)
中的位置(复数),因为它引用了表名
- it is location (singular) in
joins(:location)
because it references thebelongs_to
relationship name - it is locations (plural) in
where(…)
because it references the table name
后者意味着,如果你有以下几点:
The latter means that if you had the following:
belongs_to :location, class_name: "PublicLocation"
查询将是:
Activity.joins(:location).where(public_locations: { country: "Australia" })
这篇关于在Rails中通过它的belongs_to关系查询记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文