Switching deprecated attr_accessible to Rails 4+ Strong Parameters with gem 'cancancan'





class User < ActiveRecord::Base
  ##attr_accessible :name, :full_name, :family, :roles_mask, :password
  validates :name, :presence => true,

            :uniqueness => { :case_sensitive => false,
              :message => "is already used! Error: Duplicate Login Name." }
  validates :password, :on => :create, :presence => true
  def roles=(roles) # roles array to bitmask
    self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.sum
  end
end

class UsersController < ApplicationController
  # Use cancan authorization in all methods with support for Rails 4+ Strong Parameters
  load_and_authorize_resource param_method: :user_params
  def update
    @user.update(user_params)
  end


  def create_multiple
          new_params[:family]         = fields[0].strip
          new_params[:name]           = fields[1].strip
          new_params[:roles]          = fields[3].strip.split(/,/)  # actually sets :roles_mask
          new_params[:password] = new_params[:password_confirmation] = new_params[:name]
          @user = User.new(user_params(ActionController::Parameters.new({user: new_params}) ))
          @user.save
  end


private
    def user_params(custom_params = nil)
      custom_params ||= params
      # roles_mask, password_confirmation and password_digest

      # are not included in the permit list here:
      custom_params.require(:user).permit(:name, :family, :full_name, :valid_upto,
                            :password, roles:[]) # "roles:[]" must be the last param here.
             # See http://api.rubyonrails.org/classes/ActionController/Parameters.html
    end
end



No comments:

Post a Comment