本文介绍了Rails“未定义的 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 中写这个:

If I write this in my movies_controller.rb:

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

我有这个错误:

未定义方法 'students' for #Company::ActiveRecord_Associations_CollectionProxy:0x00000007f13d88>

如果我写这个:

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

它向我显示了我的 select_collection 中正确的学生.

it shows me the correct students in my select_collection.

如何更好地理解这个过程?

更新:

我需要这部电影的一家电影院的所有学生的 collection_select.

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

但我认为您最好按照以下方式向学生模型添加范围:

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 方法"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 20:00