首页 > 解决方案 > 范围内的 Rails 关联

问题描述

我有两个不直接相互关联的模型,ClientPotentialClient希望能够join在它们之间创建一个。

两种模型都有该字段mindbody_id,但它Location. 两者都Client属于PotentialClient一个Location

class Client < ApplicationRecord
    belongs_to :location
end

class PotentialClient < ApplicationRecord
    belongs_to :location
end

class Location < ApplicationRecord
    has_many :potential_clients
    has_many :clients
end

鉴于它既存在于 a 中又存在于 a 中,我如何Client加入PotentialClientmindbody_id Location

我认为这样的事情会起作用,但它没有:

#client.rb
has_one :potential_client, -> {
    where(potential_clients: {location_id: self.location_id, mindbody_id: self.mindbody_id})
}

标签: ruby-on-railsassociations

解决方案


我认为这应该有效

has_one :potential_client, -> { where(mindbody_id: mindbody_id }, through: :location

这应该从该位置获取所有“potential_clients”,然后应用范围,您应该只有一个 PotentialClient


推荐阅读