在我的应用程序中,这是架构:
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_york
和from_new_york
(我只关心包含两个组的集合),有没有办法写一个单.new_york
个范围可以完成这两项工作而无需编写组件.to_
和.from_
范围?