无法批量分配受保护的属性错误

时间:2013-02-28 13:48:39

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

我正在尝试创建一个teacher表,其中有一个名为'teacher_type_id'的列,即它是一个连接到teacherType表的外键,该表有三行,即1 = >导师,2 =>模块负责人和3 =>讲师。

我的schema.rb文件中包含以下信息:

create_table "teacher_types", :force => true do |t|
 t.string   "title"
 t.datetime "created_at", :null => false
 t.datetime "updated_at", :null => false
end

create_table "teachers", :force => true do |t|
 t.integer  "teacherType_id"
 t.string   "firstName"
 t.string   "lastName"
 t.datetime "created_at",     :null => false
 t.datetime "updated_at",     :null => false
end

add_index "teachers", ["teacherType_id"], :name => "index_teachers_on_teacherType_id"

teacher_typ.rb文件如下所示:

class TeacherType < ActiveRecord::Base
 has_many :teachers
 attr_accessible :title, :teacher_type_id   (Also tried :teacherType_id)
end

我的teacher.rb文件如下所示:

class Teacher < ActiveRecord::Base
  has_one :teacherType
  attr_accessible :firstName, :lastName
end

但是,现在我去localhost:3000/teacher/new并尝试使用“1”或“Tutor”作为TeacherType创建新教师,但是当我提交表单时,我总是得到相同的错误,这是:

ActiveModel::MassAssignmentSecurity::Error in TeachersController#create

Can't mass-assign protected attributes: teacherType_id
Rails.root: /Users/omar/rails_projects/attendance

Application Trace | Framework Trace | Full Trace
app/controllers/teachers_controller.rb:43:in `new'
app/controllers/teachers_controller.rb:43:in `create'

Request

Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"NEJf3bISJsidStVyfdRns0oZ7JzSZ8RqqZSAWgL9hz8=",
 "teacher"=>{"teacherType_id"=>"Tutor",
 "firstName"=>"Jack",
 "lastName"=>"Sparrow"},
 "commit"=>"Create Teacher"}`

任何想法为什么会这样?我查看了attr_accessible,但仍然无济于事

2 个答案:

答案 0 :(得分:3)

teacherType_id在TeachersController #new视图中被分配了一个字符串,但它被声明为整数。检查你的观点。另外,我避免使用混合情况下的名称,例如teacherType_id ...

答案 1 :(得分:2)

老师

attr_accessible :firstName, :lastName, :teacherType_id