Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails cancan gem won't authorize only new action

Using cancan i'm not able to create new record. I have tired to read from documentation but i can't find any help for this.

class Ability
  include CanCan::Ability

  def initialize(user)
    if user.nil?
        can :read, Branch
        can :read, Leaf
      elsif user.role? "admin"
        can :manage, :all
      else
        can :manage, Branch, :user_id => user.id
        can :manage, Leaf, :branch => { :user_id => user.id }

        # Also can read all.
        can :read, :all
    end
  end

Controller:

before_filter :authenticate_user!, :except => [:index, :show]

  def new
    @branch = Branch.new
    authorize! :new, @branch, :message => 'You are not authorized to perform this action.'
      respond_to do |format|
        format.html # new.html.erb
        format.json { render json: @branch }
      end
  end

  def create
    @branch = Branch.new(branch_params)
    authorize! :create, @branch, :message => 'You are not authorized to perform this action.'

    respond_to do |format|
      if @branch.save
        format.html { redirect_to user_branches_path(current_user.username), notice: 'Branch was successfully created.' }
      else
        format.html { render action: 'new'}
      end
    end
  end

1 Answers

Im guessing you are on rails 4, which by default uses strong parameters, it doesn't play nicely with CanCan. Its outlined in this blog. Try CanCanCan which is the continuation of the dead CanCan project.

like image 146
MPinneo Avatar answered Feb 05 '26 07:02

MPinneo