2013-02-28 74 views
0

我試圖創建一個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」或「導師」爲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但仍然無濟於事

+0

爲什麼attr可以在教師類型中訪問? – 2013-02-28 13:52:05

+0

當我在各種論壇上閱讀時遇到'attr_accessible',並且回答問題解決了這個問題。但它不是真的 – omarArroum 2013-02-28 13:54:59

+0

但attr是在老師,而不是老師類型。 – 2013-02-28 14:06:57

回答

1

教師一看:

attr_accessible :firstName, :lastName, :teacherType_id 
+0

WTF ..... O_o 我一直在玩老師模型和教師模型,然後出了任何地方,我沒有嘗試的作品......非常感謝。 順便說一句,是:has_many和:has_one正確嗎? 另外,你可以簡要說明你的代碼爲什麼起作用嗎? – omarArroum 2013-02-28 13:58:12

+0

此代碼的工作原因是,引用字段屬於Teacher(請參閱Rails doc for foreign keys explanation)。你可以看到它看到的參數:它嵌套在老師 – apneadiving 2013-02-28 14:00:52

2

teacherType_id被分配在TeachersController#新視圖的字符串,但它聲明爲一個整數。檢查你的看法。另外,我會避免使用混合案例的名稱,如teacherType_id ...

+0

+1上一致的語法 – apneadiving 2013-02-28 13:55:46

+0

同意的評論,但teacherType_id是爲teacherType模型的id。 teacher_type_id如何也是一個選項? – omarArroum 2013-02-28 13:59:37

相關問題