Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
702 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 Reply

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...