在我的應用我有屬於其他三個車型當然模式:用戶,主題和student_level(它們包括模型描述中有許多)。如何與受保護模式的工作屬性 - 外鍵(質量,分配保護錯誤)
爲了能夠創建課程,我將課程的模型中的兩個模型的外鍵聲明爲attr_accessible。
class Course < ActiveRecord::Base
attr_accessible :objectives, :title, :subject_id, :student_level_id
belongs_to :user
belongs_to :subject
belongs_to :student_level
這是我創建課程_fields.html.slim文件:
= render 'shared/error_messages', object: f.object
= f.label :title, t("activerecord.attributes.course.title")
= f.text_field :title
= f.label :subject_id, t("activerecord.attributes.subject.title")
= f.collection_select(:subject_id, Subject.all, :id, :title_for_select)
= f.label :student_level_id, t("activerecord.attributes.student_level.title")
= f.collection_select(:student_level_id, StudentLevel.all, :id, :title_for_select)
= f.label :objectives, t("activerecord.attributes.course.objectives")
= f.text_area :objectives, rows: 15, cols: 10
這是我在courses_controller.rb新方法
#GET /courses/new
def new
@course = current_user.courses.new
# @subjects = Subject.all
# @student_levels = StudentLevel.all
end
上面的代碼顯示的是我am mass-assigning subject and student level attributes。
有什麼困擾我的是,在Hartl的3.2版Ruby on Rails教程中(例如,第536頁,列表10.7),應該保護這些外鍵。並且有一個用於保護外鍵分配的例子。
現在一切正常。此外,我的config/application.rb中包含 config.active_record.whitelist_attributes =真
現在,如果我從attr_accessible刪除subject_id和student_level_id(使他們成爲受保護),應用程序提供了
ActiveModel::MassAssignmentSecurity::Error in CoursesController#create
Can't mass-assign protected attributes: subject_id, student_level_id
我的問題:創建具有兩個外鍵的實體時的最佳做法是什麼?有沒有一種方法可以創建/編輯而無需將外鍵作爲attr_accessible公開爲批量分配?
非常感謝!
UPDATE:
#POST /courses/
def create
@course = current_user.courses.new(params[:course])
if @course.save
flash[:success] = t("messages.course_created")
redirect_to @course
else
render 'new'
end
end
你可以粘貼創建動作的代碼嗎? –
@AmitThawait我更新了我的問題 - 最後添加了create方法。我無法回覆您的評論。 –
沒問題,我希望你明白我的觀點。謝謝... :-) –