【问题标题】:How to work with protected model attributes--foreign keys (mass-assignment protection error)如何使用受保护的模型属性——外键(批量分配保护错误)
【发布时间】:2013-10-11 10:47:05
【问题描述】:

在我的应用程序中,我有一个 course 模型,它属于三个其他模型:user、subject 和 student_level(它们包括 has many在模型描述中)。

为了能够创建课程,我将 course 模型中两个模型的外键声明为 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

上面的代码显示我正在批量分配 subjectstudent level 属性。

困扰我的是,在 Hartl 的 Ruby on Rails 教程 3.2 版(例如,第 536 页,清单 10.7)中,这些外键应该受到保护。还有一个受保护外键分配的例子。

现在一切正常。另外,我的 config/application.rb 包含 config.active_record.whitelist_attributes = true

现在,如果我从 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 以进行批量分配?

非常感谢!

更新:

  #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 方法。我无法回复您的评论。
  • 没问题,希望你明白我的意思。谢谢... :-)

标签: ruby-on-rails ruby-on-rails-3 foreign-keys protected attr-accessible


【解决方案1】:

通过查看课程表单my _fields.html.slim 的代码,您似乎只通过select box 从用户那里获取subject_id, student_level_id,因此它们应该可以访问。

应该保护的是:例如,你有Institue 模型和course 属于Institue,你有一个foreign_key 作为institute_id,那么这个institute_id 应该受到保护。

我可以给你的其他例子是,比如说

Project 属于UserUser 有很多projects

并且您在projects 表中有一个外键user_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 绝对不应受到保护。

【讨论】:

    猜你喜欢
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    相关资源
    最近更新 更多