【问题标题】:Rails 3.2.13 and strong_parameters exceptionsRails 3.2.13 和 strong_parameters 异常
【发布时间】:2013-04-29 01:05:05
【问题描述】:

我正在使用 Rails 3.2.13 和 strong_parameters gem。我想知道当我在开发中进行测试时是否应该从ActiveModel::ForbiddenAttributes 得到一个引发的异常?

我的 Post 模型有一个 :title:content,但如果我从许可中删除 :title,我不会收到错误消息,但我确实会被重定向回编辑页面,并带有 flash 通知,所以它被保存了记录。虽然,它并没有改变:title,这是理所当然的。这是默认行为吗?

  def post_params
    params.require(:post).permit(:content)
  end

我想知道是否需要执行其他操作才能获得引发的异常。

宝石文件:

# Gemfile
gem 'rails', '3.2.13'
gem "strong_parameters"

应用配置:

# config/application.rb
config.active_record.whitelist_attributes = false

后模型:

# post.rb model
class Post < ActiveRecord::Base
  include ActiveModel::ForbiddenAttributesProtection
end

后控制器:

# post_controller.rb
class PostsController < ApplicationController

  def update
    @post = Post.find(params[:id])
     if @post.update_attributes(post_params)
       redirect_to edit_post_path(@post), flash { success: "Post updated" }
     else
       render "edit"
     end
  end


  private

  def post_params
    params.require(:post).permit(:title, :content)
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 strong-parameters


    【解决方案1】:

    默认配置是在开发和测试环境中记录异常,甚至在生产环境中也不记录。因此,您看到的是正常行为,分配无声无息地失败。

    要引发异常,您需要更改所需环境中的默认值。 例如,config/environments/development.rb:

    # Raises an error on unpermitted attributes assignment
      config.action_controller.action_on_unpermitted_parameters = :raise  # default is :log
    

    希望对你有帮助,

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-22
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-10
      相关资源
      最近更新 更多