仅在创建新记录时出现ActiveModel :: ForbiddenAttributesError

时间:2016-03-02 09:55:27

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

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

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

请帮助!

由于

1 个答案:

答案 0 :(得分:1)

This error commonly occurs when using CanCan, authorization gem with rails >=4. To overcome this add below code to your application controller

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

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