ActiveModel::ForbiddenAttributesError when creating new user

后端 未结 7 1746
礼貌的吻别
礼貌的吻别 2020-11-22 15:59

I have this model in Ruby but it throws a ActiveModel::ForbiddenAttributesError

class User < ActiveRecord::Base
  attr_accessor :password
  v         


        
相关标签:
7条回答
  • 2020-11-22 16:54

    For those using CanCanCan:

    You will get this error if CanCanCan cannot find the correct params method.

    For the :create action, CanCan will try to initialize a new instance with sanitized input by seeing if your controller will respond to the following methods (in order):

    1. create_params
    2. <model_name>_params such as article_params (this is the default convention in rails for naming your param method)
    3. resource_params (a generically named method you could specify in each controller)

    Additionally, load_and_authorize_resource can now take a param_method option to specify a custom method in the controller to run to sanitize input.

    You can associate the param_method option with a symbol corresponding to the name of a method that will get called:

    class ArticlesController < ApplicationController
      load_and_authorize_resource param_method: :my_sanitizer
    
      def create
        if @article.save
          # hurray
        else
          render :new
        end
      end
    
      private
    
      def my_sanitizer
        params.require(:article).permit(:name)
      end
    end
    

    source: https://github.com/CanCanCommunity/cancancan#33-strong-parameters

    0 讨论(0)
提交回复
热议问题