Rails"ActiveRecord_Associations_CollectionProxy的未定义方法"

6 ruby postgresql activerecord ruby-on-rails ruby-on-rails-4

我有这个型号:

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
Run Code Online (Sandbox Code Playgroud)

如果我在movies_controller.rb中写这个:

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

我有这个错误:

未定义的方法'学生'为#Company :: ActiveRecord_Associations_CollectionProxy:0x00000007f13d88>

如果相反我写这个:

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

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

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

更新:

我需要收集这部电影电影公司中每个学生的收藏.

怎么写?

Mat*_*att 7

Nermin所述,您正在尝试从一组儿童中请求一组儿童。

您可以collect按照以下方式收集公司的学生:

@movie.cinema.companies.collect(&:students).flatten.uniq
Run Code Online (Sandbox Code Playgroud)

但是我认为您最好按照以下方式为您的Student模型添加范围:

scope :for_companies, ->(_companies) {joins(:companies).where(company: _companies)}
Run Code Online (Sandbox Code Playgroud)

Student.for_companies(@movie.cinema.companies)

免责声明:未经测试,但应作为起点!


Ner*_*min 5

@students = @movie.cinema.companies.students.all 解释为什么这会引发错误

@movie.cinema 会给你电影的电影

@movie.cinema.companies 将为您提供该电影院的公司列表 ActiveRecord_Association_CollectionProxy

然后当你调用studentsCollectionProxy通过的公司@movie.cinema.companies.students,它抛出一个错误,因为CollectionProxy没有这样的方法.

@students = @movie.cinema.companies.find(6).students.all 将会有效,因为您获得了公司列表,然后从该列表中找到一个ID为6的公司,并列出该公司的所有学生.

  • 如果能够从一系列公司中真正获得所有学生,可能会包含一些"收集"示例. (3认同)