Rails “undefined method for ActiveRecord_Associations_CollectionProxy”

前端 未结 2 662
忘了有多久
忘了有多久 2020-12-15 12:49

I have this models:

class Student < ActiveRecord::Base

    has_many :tickets
    has_many :movies, through: :tickets

end


class Movie < ActiveRecord         


        
相关标签:
2条回答
  • 2020-12-15 13:16

    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!

    0 讨论(0)
  • 2020-12-15 13:38

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

    @movie.cinema will give you cinema of the movie

    @movie.cinema.companies will give you a list of companies for that cinema as an ActiveRecord_Association_CollectionProxy

    Then when you call students on the CollectionProxy of companies via @movie.cinema.companies.students it throws an error because CollectionProxy has no such method.

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

    0 讨论(0)
提交回复
热议问题