【问题标题】:ActiveRecord::StatementInvalid in TeachersController#show and SQLite3::SQLException: no such column ErrorTeachersController#show 和 SQLite3::SQLException 中的 ActiveRecord::StatementInvalid: no such column 错误
【发布时间】:2023-03-31 08:35:02
【问题描述】:

我有两张桌子,一张叫Teacher,另一张叫Teacher_TypeTeacher 可以有多个 Teach_Types,即 John Smith 先生是模块负责人、导师和讲师(3 种教师类型)。

我在它们和它们各自的模型之间有以下关联:

class Teacher < ActiveRecord::Base
 has_and_belongs_to_many :teacher_types
 attr_accessible :first_name, :last_name, :teacher_type_ids

class TeacherType < ActiveRecord::Base
  has_and_belongs_to_many :teachers
  attr_accessible :title
end

所以现在当我尝试创建一个新的Teacher 并附有一些Teacher_Types 时,如下所示:

但是,当我按下“创建教师”按钮时,我收到以下错误消息:

我之前创建了一些Teachers,但将Teacher_Types 留空,所以即使我尝试转到localhost:3000/teachers/3,我也会收到以下错误消息(包括SQLite 浏览器以查看Teachers 中的内容表)

所以我不确定我在哪里出错了......

我的关联不正确吗?

【问题讨论】:

  • 你有teachers_teacher_typesteacher_types_teachers 桌子吗?

标签: ruby-on-rails ruby ruby-on-rails-3 sqlite ruby-on-rails-3.2


【解决方案1】:

我认为你的模型应该是这样的:

班主任

TeacherType

如果它适合你就试试吧???

【讨论】:

    【解决方案2】:

    您需要创建名为teachers_teacher_types的表

    class CreateTeachersTeacherTypes < ActiveRecord::Migration
      def change
        create_table :teachers_teacher_types, :id => false do |t|
          t.integer  :teacher_id
          t.integer :teacher_type_id
        end
      end
    end
    

    【讨论】:

    • 那么我需要改变我的关联吗?即两个型号上的belongs_to_and_has_many
    • 不,你的关联是正确的..你有表teachers_teacher_typesteacher_types_teachers
    • 我刚刚根据错误信息创建了teacher_types_teachers,它可以工作。非常感谢 ;-)
    • 顺便说一句,我需要能够为Teacher 遍历Teacher_Types 的数组,但是下面的代码似乎不起作用:&lt;%= @teacher.teacher_types.each { |type| type.title }%&gt; 我得到的是如下:教师类型: [#&lt;TeacherType id: 2, title: "Tutor", created_at: "2013-03-07 13:07:55", updated_at: "2013-03-07 13:09:24"&gt;, #&lt;TeacherType id: 3, title: "Lecturer", created_at: "2013-03-07 13:08:00", updated_at: "2013-03-07 13:08:39"&gt;]
    • Teacher Type: &lt;%= @teacher.teacher_types.map(&amp;:title).to_sentence(:last_word_connector =&gt; ' and ')%&gt;
    猜你喜欢
    • 2016-12-08
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    相关资源
    最近更新 更多