Rails cancan gem不会仅授权新动作

时间:2014-07-09 23:11:54

标签: ruby-on-rails gem cancan

使用cancan我无法创建新记录。我已经厌倦了阅读文档,但我找不到任何帮助。

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

控制器:

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 个答案:

答案 0 :(得分:1)

我猜你是在轨道4上,它默认使用强参数,它与CanCan不能很好地配合。其概述于blog。试试CanCanCan这是死CanCan项目的延续。