【问题标题】:ActiveModel::ForbiddenAttributesError only when creating a new recordActiveModel::ForbiddenAttributesError 仅在创建新记录时发生
【发布时间】:2016-06-15 02:25:33
【问题描述】:

我已将我的 app rails 版本从 3.2.13 升级到 4.2.1,所以 每当我尝试创建新记录时,我都会收到ActiveModel::ForbiddenAttributesError

我正在使用 rails4.2.1。

这是我的控制器

class CategoriesController < ApplicationController
  load_and_authorize_resource

  before_action :set_category, only: [:edit, :show, :update, :destroy]

  def index

  end

  def show
  end

  def new
    @category = Category.new
  end

  def create
    @category = Category.new(category_params)
    if @category.save
      redirect_to @category, :notice => "Successfully created category."
    else
      render :action => 'new'
    end
  end

  def edit
  end

  def update
    if @category.update_attributes(category_params)
      redirect_to @category, :notice  => "Successfully updated category."
    else
      render :action => 'edit'
    end
  end

  def destroy
    @category.destroy
    redirect_to categories_url, :notice => "Successfully destroyed category."
  end

  private

    def set_category
      @category = Category.find(params[:id])
    end

    def category_params
      params.require(:category).permit(:name)
    end
end

每当我更新现有类别时,都没有问题。类别更新成功。

请帮忙!

谢谢

【问题讨论】:

    标签: ruby-2.2 rails-4-2-1


    【解决方案1】:

    此错误通常在使用 CanCan、rails >=4 的授权 gem 时发生。 为了克服这个问题,将下面的代码添加到您的应用程序控制器中

    before_action do  
      resource = controller_name.singularize.to_sym
      method = "#{resource}_params"
      params[resource] &&= send(method) if respond_to?(method, true)
    end 
    

    来源:https://github.com/ryanb/cancan/issues/835#issuecomment-18663815

    【讨论】:

      猜你喜欢
      • 2013-06-24
      • 2016-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多