代码之家  ›  专栏  ›  技术社区  ›  Carl Edwards monkbroc

在WHERE子句中查找父级的父级

  •  0
  • Carl Edwards monkbroc  · 技术社区  · 8 年前

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

    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 回复  |  直到 8 年前
        1
  •  0
  •   Josh Brody    8 年前

    .where(state: state) 静态查询 state 在 Restaurant .

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