Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
677 views
in Technique[技术] by (71.8m points)

ruby - Rails "undefined method for ActiveRecord_Associations_CollectionProxy"

I have this 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 movies_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 the collection_select of every students in companies of a cinema of this movie.

How to write?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

You could use collect to gather the students from the companies along the lines of:

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

But I think you would do better to add a scope to your Student model along the lines of:

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

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

Disclaimer: untested, but should be a starting point!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...