首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过给定id的搜索在has_many中查找第一个和最后一个对象

通过给定id的搜索在has_many中查找第一个和最后一个对象
EN

Stack Overflow用户
提问于 2017-10-29 08:53:46
回答 1查看 128关注 0票数 0

首先,我是铁轨初学者,请不要通过西红柿对我说:)我有模型:

代码语言:javascript
复制
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_from
  • railway_station.last.id = station_last

我知道我需要用joins.where,但不知道怎么用.

更新这段代码可以工作,但我认为有一个更好的解决方案:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2017-10-29 10:40:29

我不知道你想如何在铁路关系中对火车站进行分类。我认为您需要向RailwayStationsRoute中添加数字以进行排序。

一般来说,你可以这样做:

代码语言:javascript
复制
rw_from = RaillwayStation.find(1)
rw_to = RaillwayStation.find(2)
trains = Train.where(route: rw_from.routes & rw_to.routes)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46998397

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档