0

我已将我的 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

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

请帮忙!

谢谢

4

1 回答 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

于 2016-03-02T11:00:11.593 回答