Rails "undefined for ActiveRecord_Associations_CollectionProxy"

I have these models:

class Student < ActiveRecord::Base has_many :tickets has_many :movies, through: :tickets end class Movie < ActiveRecord::Base has_many :tickets, dependent: :destroy has_many :students, through: :tickets belongs_to :cinema end class Ticket < ActiveRecord::Base belongs_to :movie, counter_cache: true belongs_to :student end class Cinema < ActiveRecord::Base has_many :movies, dependent: :destroy has_many :students, through: :movies has_many :schools, dependent: :destroy has_many :companies, through: :yard_companies end class School < ActiveRecord::Base belongs_to :company belongs_to :student belongs_to :cinema, counter_cache: true end class Teacher < ActiveRecord::Base belongs_to :movie, counter_cache: true belongs_to :company end class Contract < ActiveRecord::Base belongs_to :company belongs_to :student end class Company < ActiveRecord::Base has_many :teachers has_many :movies, through: :teachers has_many :contracts has_many :students, through: :contracts end 

If I write this in my movie_controller.rb :

@students = @movie.cinema.companies.students.all

I have this error:

undefined method 'students' for #Company :: ActiveRecord_Associations_CollectionProxy: 0x00000007f13d88>

If instead I write this:

@students = @movie.cinema.companies.find(6).students.all

it shows me the correct students in my select_collection.

How to better understand this process?

UPDATE

I need to collect_select each student in the movie theater companies of this movie.

How to write?

+5
source share
2 answers

As described by Nermin , you are trying to request a collection of children from a collection of children.

You can use collect to collect students from companies according to:

 @movie.cinema.companies.collect(&:students).flatten.uniq 

But I think that you better add an area for your Student model according to:

 scope :for_companies, ->(_companies) {joins(:companies).where(company: _companies)} 

Called by Student.for_companies(@movie.cinema.companies)

Disclaimer: Unverified, but should be the starting point!

+3
source

@students = @movie.cinema.companies.students.all to explain why this causes an error

@movie.cinema will give you a movie about cinema

@movie.cinema.companies will provide you with a list of companies for this movie theater like ActiveRecord_Association_CollectionProxy

Then, when you call students at CollectionProxy companies through @movie.cinema.companies.students , it throws an error because CollectionProxy does not have such a method.

@students = @movie.cinema.companies.find(6).students.all will work because you get a list of companies, then from this list you will find one company with identifier 6 and list all students for this single company.

+5
source

All Articles