首先,我是铁轨初学者,请不要通过西红柿对我说:)我有模型:
class RailwayStation < ApplicationRecord
has_many :trains, foreign_key: :current_station_id
has_many :railway_stations_routes
has_many :routes, through: :railway_stations_routes
end
class Route < ApplicationRecord
has_many :railway_stations_routes
has_many :trains
has_many :railway_stations, through: :railway_stations_routes
end
class RailwayStationsRoute < ApplicationRecord
belongs_to :railway_station
belongs_to :route
end
class Train < ApplicationRecord
belongs_to :current_station, class_name: 'RailwayStation', foreign_key: :current_station_id
belongs_to :route
has_many :tickets
has_many :wagons
end例如,station_from =1和station_last =9,现在我需要找到所有沿着路线行驶的列车。在路线上我需要条件:
railway_station.first.id = station_fromrailway_station.last.id = station_last我知道我需要用joins.where,但不知道怎么用.
更新这段代码可以工作,但我认为有一个更好的解决方案:
routes_from = Route.joins(:railway_stations).where('railway_stations.id': 1)
routes_to = Route.joins(:railway_stations).where('railway_stations.id': 2)
routes_from.each do |route_from|
routes_to.where(id: route_from).each do |route|
route.trains.each do |train|
@trains ||= []
@trains << train
end
end
end发布于 2017-10-29 10:40:29
我不知道你想如何在铁路关系中对火车站进行分类。我认为您需要向RailwayStationsRoute中添加数字以进行排序。
一般来说,你可以这样做:
rw_from = RaillwayStation.find(1)
rw_to = RaillwayStation.find(2)
trains = Train.where(route: rw_from.routes & rw_to.routes)https://stackoverflow.com/questions/46998397
复制相似问题