【问题标题】:Unable to configure cancancan in Rails无法在 Rails 中配置 cancancan
【发布时间】:2019-02-20 21:34:26
【问题描述】:

我正在使用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

用户.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

目标

我的目标是不允许访客用户创建新帖子。

问题

虽然我已经在 ability.rb 中明确定义了不同类型的用户可以做什么,但我却被拒绝访问管理员和访客用户的问题。

如果您需要有关代码的更多信息,可以在github 上查看。

提前谢谢你。

【问题讨论】:

    标签: ruby-on-rails activeadmin cancancan


    【解决方案1】:

    问题是您正在覆盖传递给 Ability 类的user。删除这一行:

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

    【讨论】:

    • 我已经删除了该行,但功能仍然与以前相同。你可能想看看我刚刚添加的 user.rb。
    猜你喜欢
    • 1970-01-01
    • 2015-12-01
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-25
    相关资源
    最近更新 更多