簡體   English   中英

無法在Rails中配置cancancan

[英]Unable to configure cancancan in Rails

我正在使用active_admincancancan gem。

ability.rb

    if user.admin?
        can :manage, :all
    elsif user.regular?
        can :read, :all
    else 
        can :read, :all 
    end

我在數據庫中有role列。 它基本上是一個博客。

schema.rb

ActiveRecord::Schema.define(version: 2019_02_18_221247) do

  create_table "active_admin_comments", force: :cascade do |t|
    t.string "namespace"
    t.text "body"
    t.string "resource_type"
    t.integer "resource_id"
    t.string "author_type"
    t.integer "author_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["author_type", "author_id"], name: "index_active_admin_comments_on_author_type_and_author_id"
    t.index ["namespace"], name: "index_active_admin_comments_on_namespace"
    t.index ["resource_type", "resource_id"], name: "index_active_admin_comments_on_resource_type_and_resource_id"
  end

  create_table "categories", force: :cascade do |t|
    t.string "category"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "posts", force: :cascade do |t|
    t.string "title"
    t.text "body"
    t.integer "user_id"
    t.date "published_at"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "category_id"
  end

  create_table "users", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "role"
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end

end

user.rb

class User < ApplicationRecord
    has_many :posts
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, 
         :recoverable, :rememberable, :validatable
  def admin?
    role == "admin"
  end
  def regular?
    role == "regular"
  end
  def guest?
    role == "guest"
  end
end

目標

我的目標是不允許訪客用戶創建新帖子。

問題

盡管我已經在能力.rb中明確定義了不同類型的用戶可以執行的操作,但管理員和來賓用戶都拒絕訪問該問題。

如果您需要有關代碼的更多信息,可以在github上進行檢查。

先感謝您。

問題是,你正在覆蓋user則傳遞的能力類。 刪除此行:

user = User.new(role: "guest")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM