在where子句中找到父母的父母

时间:2018-07-18 22:15:25

标签: sql ruby-on-rails activerecord

我有一家餐厅,它属于一个城市,属于一个州:

class Restaurant < ApplicationRecord
  belongs_to :city
end

class City < ApplicationRecord
  belongs_to :state
end

class State < ApplicationRecord
  has_many :cities
end

我想在餐厅模型中创建一个范围,以查找其所居住城市的给定州。到目前为止,我已经做到了:

scope :by_state, -> state { joins(city: :state).includes(city: [:state]).where(state: state) }

不幸的是,这给了我错误:

ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR: column restaurants.state does not exist)

我在这里做什么错了?

1 个答案:

答案 0 :(得分:0)

.where(state: state)仍在state上查询Restaurant

scope :by_state, -> state { joins(city: :state).includes(city: [:state]).where('states.name = ?', state) }可能就是您想要的。