ActiveRecord范围 - 通过两个不同的外键嵌套关联

时间:2014-10-14 15:26:31

标签: sql ruby-on-rails activerecord ruby-on-rails-4

在我的应用程序中,这是架构:

class Route < ActiveRecord::Base
  belongs_to :origin, class_name: 'Station'
  belongs_to :destination, class_name: 'Station'
  belongs_to :vehicle

  has_many :trips 
end

class Trip < ActiveRecord::Base
  belongs_to :route
end

class Station < ActiveRecord::Base
  has_many :origins, foreign_key: :origin_id, class_name: "Route"
  has_many :destinations, foreign_key: :destination_id, class_name: "Route"
end

我正在尝试在Trip内构建一个范围,用于获取从特定Station飞往OR的所有旅程。现在,我正在完成以下.new_york范围:

scope :to_new_york,       -> { joins(route: :destination).where(["stations.name = ?", "New York City"]) }
scope :from_new_york,     -> { joins(route: :origin).where(["stations.name = ?", "New York City"]) }
scope :new_york,          -> { to_new_york + from_new_york }

由于我从不打算自己使用to_new_yorkfrom_new_york(我只关心包含两个组的集合),有没有办法写一个单.new_york个范围可以完成这两项工作而无需编写组件.to_.from_范围?

0 个答案:

没有答案