Sql 在where子句中查找父级的父级

Sql 在where子句中查找父级的父级,sql,ruby-on-rails,activerecord,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 不幸的是,这给了我一个错误: ActiveRecord::StatementInvalid

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

class Restaurant < ApplicationRecord
  belongs_to :city
end

class City < ApplicationRecord
  belongs_to :state
end

class State < ApplicationRecord
  has_many :cities
end
不幸的是,这给了我一个错误:

ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR: column restaurants.state does not exist)
我在这里做错了什么?

。where(state:state)
仍然在
餐厅上查询
state


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

我能像我原来的帖子那样简单地查询id和名称吗?你必须将
states.name
更改为
states.id
,但这应该行得通。非常感谢。我的设置中唯一的一点是,尽管在范围中使用了include,但我仍然渴望加载(根据bullet gem)。你知道为什么吗?上面说什么?未使用?
eagent loading=>[:city]添加到您的finder::includes=>[:city]
ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR: column restaurants.state does not exist)