Rails“ ActiveRecord_Associations_CollectionProxy的未定义方法”; [英] Rails "undefined method for ActiveRecord_Associations_CollectionProxy"
问题描述
我有这个模型:
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
如果我在 movies_controller.rb中写这个:
@students = @ movie.cinema.companies.students.all
我遇到此错误:
#Company :: ActiveRecord_Associations_CollectionProxy:0x00000007f13d88>的未定义方法学生>
相反,我这样写:
@students = @movie。 Cinema.companies.find(6).students.all
它向我显示了我选择的学生中正确的学生。
it shows me the correct students in my select_collection.
如何更好地理解此过程?
更新:
我需要这部电影的电影公司的每个学生的全集。
I need the collection_select of every students in companies of a cinema of this movie.
如何
推荐答案
如 Nermin 您正在尝试从一组儿童中请求一组儿童。
As described by Nermin you're trying to request a collection of children, from a collection of children.
您可以使用 collect
沿以下路线收集公司的学生:
You could use collect
to gather the students from the companies along the lines of:
@movie.cinema.companies.collect(&:students).flatten.uniq
但是我认为您最好按照以下方式为您的Student模型添加范围:
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)}
用 Student.for_companies(@ movie.cinema.companies)
免责声明:未经测试,但应该作为起点!
Disclaimer: untested, but should be a starting point!
这篇关于Rails“ ActiveRecord_Associations_CollectionProxy的未定义方法”;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!