从Active Record Association Relation返回唯一对象

时间:2015-03-22 09:26:37

标签: ruby-on-rails activerecord

我遇到一个简单的has_many关系。我正在尝试返回唯一的对象,但因为我在关系中间对对象施加限制,所以我在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"

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

Customer.rb

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

但where语句加载了一个活动的记录关联对象。如何包含此条件并仍然返回独特的培训师?

3 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:1)

试试这个:

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

答案 2 :(得分:1)

我试试这个:

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