如何通过关系查询has_one?

How to query has_one through relationship?

我的模特:
metro_station.rb

class MetroStation < ActiveRecord::Base
  belongs_to :metro_line
  has_one :city, through: :metro_line, autosave: false
end

metro_line.rb`

class MetroLine < ActiveRecord::Base
  belongs_to :city
  has_many :metro_stations
end

city.rb

class City < ActiveRecord::Base
  has_many :metro_lines
end

当我运行:
MetroStation.where(city: City.first)
我得到

PG::UndefinedColumn: ERROR:  column metro_stations.city_id does not exist
: SELECT "metro_stations".* FROM "metro_stations" WHERE "metro_stations"."city_id" = 1
(pry) output error: #<ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column metro_stations.city_id does not exist
LINE 1: ...CT "metro_stations".* FROM "metro_stations" WHERE "metro_sta...

虽然此查询有效:
MetroStation.joins(:metro_line).where(metro_lines: {city_id: 1})

要找出第一种方法不起作用的原因,请输入

MetroStation.where(city: City.first).to_sql

您应该会看到类似

的内容
... WHERE metro_stations.city_id = 1

构成查询的一部分。 MetroStation 模型根本没有 city_id 属性,因此您的第一种方法形成了无效的 SQL 语句。

连接有效,因为它在 MetroLine table 上过滤,它与 city_id 字段形式的城市模型有关系。

您的模型没有问题,只是 Rails 生成 SQL 语句的方式在 SQL 的世界中是有意义的。

City 到 MetroStation 通过 MetroLine 的 has_many 关系为您的问题(城市中有哪些地铁站)提供了所需的结果。

例子

class City < ActiveRecord::Base
  has_many :metro_lines
  has_many :metro_stations, through: :metro_lines
end

class MetroLine < ActiveRecord::Base
  belongs_to :city
  has_many :metro_stations
end

class MetroStation < ActiveRecord::Base
  belongs_to :metro_line
  has_one :city, through: :metro_line
end


# Return all metro stations for a city
# * assuming City has name 'name' field
london_stations = City.find_by_name('London').metro_stations 

希望对您有所帮助!

城市还应:

has_many :metro_stations, :through => :metro_lines

然后你写:

City.first.metro_stations