Rails5 如何在多个共享属性的表之间形成关联

Rails 5 how to form association between tables on multiple shared attributes

在Rails5中,给定两个表之间的关系,涉及将它们连接到多个共享属性上,我如何在这些表对应的模型之间形成关联?

SQL:

SELECT *
FROM trips
JOIN stop_times ON trips.guid = stop_times.trip_guid AND trips.schedule_id = stop_times.schedule_id

我试过下面的配置,一般都能用...

class Trip < ApplicationRecord
  has_many :stop_times, ->(trip){ where("stop_times.schedule_id = ?", trip.schedule_id) }, :inverse_of => :trip, :primary_key => :guid, :foreign_key => :trip_guid, :dependent => :destroy
end

class StopTime < ApplicationRecord
  belongs_to :trip, :inverse_of => :stop_times, :primary_key => :guid, :foreign_key => :trip_guid
end

Trip.first.stop_times.first #> StopTime object, as expected
Trip.first.stop_times.first.trip #> Trip object, as expected

...但是当我尝试在更高级的查询中使用它时,它会触发 ArgumentError: The association scope 'stop_times' is instance dependent (scope block takes an argument)。不支持预加载实例相关范围。...

Trip.joins(:stop_times).first #=> the unexpected ArgumentError
StopTime.joins(:trip).first #> StopTime object, as expected

我知道错误指的是什么,但我不确定如何修复它。

编辑:

我希望一个协会就足够了,但有人注意到两个不同的协会可以完成这项工作:

class Trip < ApplicationRecord
  has_many :stop_times, 
              ->(trip){ where("stop_times.schedule_id = ?", trip.schedule_id) }, 
              :primary_key => :guid, 
              :foreign_key => :trip_guid # use trip.stop_times instead of trip.joined_stop_times to avoid error about missing attribute due to missing join clause

  has_many :joined_stop_times, 
            ->{ where("stop_times.schedule_id = trips.schedule_id") },
            :class_name => "StopTime",
            :primary_key => :guid,
            :foreign_key => :trip_guid # use joins(:joined_stop_times) instead of joins(:stop_times) to avoid error about instance-specific association
end

Trip.first.stop_times
Trip.eager_load(:joined_stop_times).to_a.first.joined_stop_times # executes a single query

如果阅读本文的任何人知道如何使用单个关联,请提及我。

我认为这不是正确的解决方案,但它可以提供帮助。您可以添加另一个类似的实例独立关联,该关联将仅用于预加载。它适用于 :joins:eager_load 但不适用于 :includes.

class Trip < ApplicationRecord
  has_many :preloaded_stop_times, 
           -> { where("stop_times.schedule_id = trips.schedule_id") },               
           class_name: "StopTime", 
           primary_key: :guid, 
           foreign_key: :trip_guid
end

# Usage
trips = Trip.joins(:preloaded_stop_times).where(...)
# ...

# with :eager_load
trips = Trip.eager_load(:preloaded_stop_times)

trips.each do |trip|
  stop_times = trip.preloaded_stop_times
  # ...
end