1

在我的應用我有屬於其他三個車型當然模式:用戶,主題和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 
+0

你可以粘貼創建動作的代碼嗎? –

+0

@AmitThawait我更新了我的問題 - 最後添加了create方法。我無法回覆您的評論。 –

+0

沒問題,我希望你明白我的觀點。謝謝... :-) –

回答

0

通過看你的課程形式my _fields.html.slim的代碼,它看起來像你只能通過select box採取從用戶subject_id, student_level_id,所以他們應該是可訪問的。

應該保護什麼是:比方說,你有Institue模型和course屬於一個Institue和你有一個foreign_keyinstitute_id,那麼這個institute_id應該受到保護。

其他例子,我可以給你的是,說

Project belongs_to的UserUser有很多projects

,你有一個外鍵projectsuser_id

然後同時建立了項目你應該這樣做:

#This will create a new project object with user_id set as id of current_user 
current_user.projects.new 

我們創建一個項目對象使用參數:

current_user.projects.new(params[:project]) 

我不知道的是,他們的任何方式來創建二級保護屬性,但肯定是在屬性subject_id, student_level_id不應該保護你的情況的對象。

相關問題