从 Active Record 关联关系返回唯一对象

Returning unique object from Active Record Association Relation

我在处理简单的 has_many 关系时遇到了问题。我正在尝试 return 独特的对象,但是因为我在关系中间对对象施加了限制,所以我在 ActiveRecord_AssociationRelation.

上得到了一个未定义的方法

我有:

class Customer < ActiveRecord::Base
 has_many :session_enrollments
 has_many :session_details, through: :session_enrollments


class SessionDetail < ActiveRecord::Base
 has_many :customers, through: :session_enrollments
 belongs_to :trainer

class Trainer < ActiveRecord::Base

 has_many :session_details
 has_many :session_enrollments, through: :session_details
 has_many :customers, through: :session_enrollments


class SessionEnrollment < ActiveRecord::Base

 belongs_to :customer, :foreign_key => "customer_id"
 belongs_to :session_detail, :foreign_key => "session_detail_id"

我正在尝试 return 通过以下方式与客户进行当前会话的所有培训师:

Customer.rb

@trainers = self.session_details.where(state: ["CONFIRMED"]).trainers

但是where 语句加载了一个活动记录关联对象。我怎样才能包含这个条件并且仍然 return 独特的培训师?

我假设 stateCustomer 中的一个列,您需要加入记录,试试这个

@trainers = self.includes(:session_details => :trainer).where(session_details: {state: ["CONFIRMED"]})

此查询将 return 客户及其与相关培训师的会话详细信息

试试这个:

@trainers = Trainer.joins(:session_details, :customers).where(session_details: {state: "CONFIRMED"}).where(customers: {id: self.id}).distinct

我会试试这个:

@trainers = Trainer.joins(session_details: [:session_enrollments]).where(session_details: {state: 'CONFIRMED'}).where(session_enrollments: {customer_id: self.id}).distinct