通过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')
- 用户团队应用程序
- Heroku“psql:FATAL:剩余的连接插槽保留用于非复制超级用户连接”
- 怎么逃避? (问号)运算符在Rails中查询Postgresql JSONB类型
- Rails:after_create停止保存时出现exception
- 多对多关系只能以Rails / Activerecord / devise的方式工作
- Rails应用程序错误 – ActiveRecord :: PendingMigrationError正在等待迁移; 运行’rake db:migrate RAILS_ENV = development’来解决此问题
- 在Rails和ActiveRecord中查询时忽略某些字段
- 帮助rails活动记录查询(如子句)
- 如何在Rails 3中使用“额外描述”生成数据类型的脚手架?