【问题标题】:Rails association within a scope范围内的 Rails 关联
【发布时间】:2019-12-11 12:41:31
【问题描述】:

我有两个不直接相互关联的模型Client 和PotentialClient,我希望能够在它们之间创建一个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

考虑到 mindbody_id 存在于 Client 和 PotentialClient 中并且在 Location 中是唯一的,我如何加入 mindbody_id?

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

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

【问题讨论】:

    标签: ruby-on-rails associations


    【解决方案1】:

    我认为这应该可行

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

    这应该从该位置获取所有“潜在客户”,然后应用范围,您应该只有一个潜在客户

    【讨论】:

    • 它抛出一个错误,因为位置 has_many :potential_clients: ActiveRecord::HasManyThroughSourceAssociationNotFoundError: 在模型位置中找不到源关联“potential_client”或:potential_client。尝试 'has_many :potential_client, :through => :location, :source => '。它是评论、潜在客户、用户、员工、客户、签到、称重、每周报告、咨询统计或 mind_body_sales 之一?
    • 我猜是has_one ....., through: :location, source: :potential_clients
    猜你喜欢
    • 2013-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 2015-06-25
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多