DaynaJuliana
DaynaJuliana

Reputation: 1164

Returning unique object from Active Record Association Relation

I'm having trouble with a simple has_many relationship. I'm trying to return unique objects, but because I'm putting restraints on the object in the middle of the relationship, I'm getting an undefined method on my ActiveRecord_AssociationRelation.

I have:

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"

I'm trying to return all trainers that have a current session with a customer via:

Customer.rb

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

But the where statement loads an active record association object. How can I include this condition and still return the unique trainers?

Upvotes: 0

Views: 1189

Answers (3)

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

I'm assuming that state is a column in Customer, You need to join the records, try this instead

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

This query will return customer along with their session details with associated trainers

Upvotes: 1

Almaron
Almaron

Reputation: 4147

I'd try this:

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

Upvotes: 1

Sharvy Ahmed
Sharvy Ahmed

Reputation: 7405

Try this:

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

Upvotes: 1

Related Questions