2013-03-02 23 views
0

這是一個後續問題Can't Mass Assign Protected Attributes ErrorCollection_Select不是我的模型分配值

我試圖用一個Colleciton_Select,這樣我可以從下拉框中TeacherType,而不是讓用戶來寫teacherType_id。

<%= collection_select(:teacherType, :teacherType_id, TeacherType.order('title'), :id, :title, :prompt => true) %>

然而,當我從下拉菜單中的選項,它總是說教師已成功更新,但是沒有在教師模型變化。

我做錯了什麼?

+0

它是形式嗎? – codeit 2013-03-02 14:06:55

+1

試試這個<%= collection_select(:teacher,:teacherType_id,TeacherType.order('title'),:id,:title,:prompt => true)%> – 2013-03-02 14:07:37

+0

你能發表你的params嗎? – codeit 2013-03-02 14:12:29

回答

1

第一件事,我想你想添加的teacherTypeTeacher而不是TeacherType所以你應該使用

<%= collection_select(:teacher, :teacherType_id, TeacherType.order('title'), :id, :title, :prompt => true) %> 

現在,第二點我想提一提,如果你在一個模型中有has_many協會那麼你應該總是有belongs_to協會在其他。

所以修改關聯定義在Teacher模型從

has_one :teacherType 

到其他

belongs_to :teacherType 

一個點上,其良好的做法有關聯的名稱作爲相關模型的下劃線多元化的形式。 Convention over configuration is the way rails applications are supposed to be built.如果在任何情況下您都不能擁有此名稱,那麼您必須將class_name屬性指定爲關聯定義。

+0

因此,每當我有'has_many',我需要一個'belongs_to'?但從字面上看,在我的腦海中,有道理的說TeacherType有很多老師,而老師模型只有一個老師類型與之相關聯...... 另外,我不太清楚你的答案的後半部分是什麼意思,你是指我的'TeacherType'模型嗎?你的意思是我應該把它叫做Teacher_Type嗎? – omarArroum 2013-03-02 16:37:16

+0

不,我的意思是你應該寫'belongs_to:teacher_type'。 – 2013-03-02 16:42:32

+0

其實'belongs_to'關聯是在我們保留foreign/association關鍵字的模型中定義的。而且,屬於一個羣體/類型的人比擁有一個羣體/類型更有意義。 – 2013-03-02 16:48:58