如何使用double belongs_to关联查询

时间:2016-01-25 17:09:33

标签: ruby-on-rails postgresql ruby-on-rails-4

我有3个型号:

活动,地点,位置

Event:
  belongs_to :place

Place:
  belongs_to :location

Location:
  has_many :places

我想查找Location的city属性为'New York'的所有事件。使用Rails4和Postgres的最佳方法是什么?

3 个答案:

答案 0 :(得分:2)

这应该

Event.includes({ place: :locations }).where(locations: {city: 'New York'}).references(:locations)

答案 1 :(得分:1)

尝试

Event.joins(:place => :location).where("locations.city = ?", "New York")

答案 2 :(得分:0)

你想要使用nested associations(特别是第12.2.3节)

Event.joins(places: :locations).where('locations.city = ?', 'New York')