Rails Includes Error : UndefinedTable: ERROR: missing FROM-clause entry for table

Rails Includes Error : UndefinedTable: ERROR: missing FROM-clause entry for table

我更喜欢使用包含来连接我的三个表。我需要连接三个模型,例如 Register、Student 和 Schedule。这是我的模型协会

class Student < ApplicationRecord
    belongs_to :register
end

class Register < ApplicationRecord
    has_one :student

    belongs_to :schedule
end

class Schedule < ApplicationRecord
    belongs_to :course
    belongs_to :teacher

    has_many :days, :dependent => :destroy, :class_name => 'ScheduleDay'
    has_many :registers
end

这是我的控制器

def index
        @students = Student.includes([register: :schedule])
        @students = @students.order 'students.created_at DESC'


        if params[:status_id] && params[:status_id].to_i > 0
            @students = @students.where 'students.status_id = ?', params[:status_id]
        end

        if params[:id] && params[:id].to_i > 0
            @students = @students.where 'cast(students.id as varchar) like (?)', "%#{params[:id]}%"
        end

        if params[:full_name] && params[:full_name].to_s.length > 0
            @students = @students.where 'lower(registers.name_in_indonesian || registers.name_in_chinese) like lower(?)', "%#{params[:full_name]}%"
        end

        if params[:course_id] && params[:course_id].to_i > 0
            @students = @students.where 'schedules.course_id = ?', params[:course_id]
        end

        @students = @students.paginate(page: params[:page], per_page: 30)
end

我收到以下错误:

PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "schedules"
LINE 1: SELECT "students".* FROM "students" WHERE (schedules.course_...

我尝试使用 rails 控制台进行调试,但结果是 (对象不支持 #inspect)

我认为您正在进行一些未迁移的迁移。请运行

rake db:migrate

在 运行ning 上述命令后重新启动 rails 控制台,然后尝试相同的操作。您不会收到此错误。

你需要 join those tables if you want to query them, includes 还不够:

@students = Student.joins(register: :schedule)

或添加一个references调用:

@students = Student.includes(register: :schedule).references(register: :schedule)

includes 将减少访问包含表的数据库查询次数,但不会加入表。