Rails 5 - Rolify - 尝试从用户中删除角色的实例

时间:2016-11-25 01:10:46

标签: ruby-on-rails ruby associations rolify

我正在尝试学习如何在我的Rails 5应用程序中使用rolify。

我之前问过很多关于Rolify的问题,最近here但是我找不到帮助。

我努力想弄清楚如何从用户中删除指定的角色。

我的架构中的表包含app_roles表(这是我用于制作可以单独分配给用户的角色的CRUD),用户,角色和user_roles - 如下:

create_table "app_roles", force: :cascade do |t|
    t.string   "title"
    t.string   "display_name"
    t.integer  "category"
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
  end

  create_table "users", force: :cascade do |t|
    t.string   "first_name"
    t.string   "last_name"
    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.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.inet     "current_sign_in_ip"
    t.inet     "last_sign_in_ip"
    t.string   "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    t.string   "unconfirmed_email"
    t.integer  "failed_attempts",        default: 0,  null: false
    t.string   "unlock_token"
    t.datetime "locked_at"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    t.integer  "organisation_id"
    t.index ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true, using: :btree
    t.index ["email"], name: "index_users_on_email", unique: true, using: :btree
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
    t.index ["unlock_token"], name: "index_users_on_unlock_token", unique: true, using: :btree
  end

  create_table "users_roles", id: false, force: :cascade do |t|
    t.integer "user_id"
    t.integer "role_id"
    t.index ["user_id", "role_id"], name: "index_users_roles_on_user_id_and_role_id", using: :btree
  end

create_table "roles", force: :cascade do |t|
    t.string   "name"
    t.string   "resource_type"
    t.integer  "resource_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.index ["name", "resource_type", "resource_id"], name: "index_roles_on_name_and_resource_type_and_resource_id", using: :btree
    t.index ["name"], name: "index_roles_on_name", using: :btree
  end

协会是:

用户

rolify strict: true # strict means you get true only on a role that you manually add
  attr_accessor :current_role

作用

has_and_belongs_to_many :users, :join_table => :users_roles

  belongs_to :resource,
             :polymorphic => true,
             :optional => true

App角色(没有关联 - 它是我用来通过表单创建新角色的CRUD)

我的用户模型有:

class User < ApplicationRecord
  rolify strict: true # strict means you get true only on a role that you manually add
  attr_accessor :current_role

我无法弄清楚如何使用rolify按照wiki中显示的方式分配角色。这就是我制作单独资源的原因。它被称为分配角色。我有一个assign_roles_controller.rb,其中包含:

class Users::AssignRolesController < ApplicationController

  before_action :authenticate_user!

  def index
      @app_roles = AppRole.all
  end


  def create
    user = User.find(params[:users])
    role = AppRole.find(params[:roles])
    organisation = Organisation.find(current_user.organisation)
     # byebug

    user.add_role role.display_name, organisation

    flash[:notice] = "Successfully created"
    redirect_to action: :index
  end

  def show
    @users = User.all
  end

  def update
  end

  def destroy

    # user = User.find(params[:users])
    # user = User.find(params[:id])
    user = User.find_by_id(params[:id])
    # User.find(params[:id])
    # role = AppRole.find(params[:roles])
    role = params[:user][:roles]
    # assigned_role = user.roles
    # user_roles = user.roles
    # organisation = Organisation.first
    organisation = Organisation.find(current_user.organisation)

    # byebug

    user.remove_role role.display_name, organisation

    flash[:notice] = "Successfully created"
    redirect_to root_path
  end

end

路由是嵌套的,所以我有:

resources :users, shallow: true do
    scope module: :users do
      resources :assign_roles

在我的用户索引中,我尝试显示用户列表,其中包含每个角色和删除角色链接。在users / index.html.erb中,我有:

<% user.roles.each do |role| %>
              <table class="table table-bordered">
              <tr>
                <td><%= role.name.titleize %></td>
                <td><%= link_to 'Remove role', assign_role_path(user.roles),  method: :delete, data: { confirm: 'Are you sure?' } %></td>
              </tr>
              </table>
             <% end %>

在控制台中,我可以这样做:

Organisation.find_roles(nil, User.find_by(organisation_id:1))
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."organisation_id" = $1 LIMIT $2  [["organisation_id", 1], ["LIMIT", 1]]
  Role Load (0.7ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (resource_type IN ('Organisation'))  [["user_id", 43]]
 => #<ActiveRecord::AssociationRelation [#<Role id: 3, name: "asdf", resource_type: "Organisation", resource_id: 1, created_at: "2016-10-24 23:00:40", updated_at: "2016-10-24 23:00:40">, #<Role id: 4, name: "ffff", resource_type: "Organisation", resource_id: 1, created_at: "2016-11-09 00:26:56", updated_at: "2016-11-09 00:26:56">]> 

用户有两个角色。

当我尝试删除其中一个时,我收到一条错误消息:

undefined method `[]' for nil:NilClass

该错误在我的分配角色控制器的销毁操作中抱怨此公式(这是某人对另一个SO帖子的建议的副本):

role = params[:user][:roles]

当我尝试将destroy动作作为:

def destroy
    user = User.find_by_id(params[:id])
    assigned_role = user.roles
    organisation = Organisation.find(current_user.organisation)

    # byebug

    user.remove_role assigned_role.display_name, organisation

    flash[:notice] = "Successfully created"
    redirect_to root_path
  end

然后我得到一个错误,上面写着:

undefined method `roles' for nil:NilClass

我认为该错误可能与我试图从用户中删除一个角色有关,但我使用复数来找到它们。我不确定如何找到我在使用索引中引用的特定角色。

任何人都可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

请参考一次。

 def destroy
    user = User.find_by_id(params[:id])
    assigned_role = user.role_name
    organisation = Organisation.find(current_user.organisation)

    # byebug

    user.remove_role assigned_role, organisation

    flash[:notice] = "Successfully created"
    redirect_to root_path
  end

答案 1 :(得分:1)

我参加了一个关于代码的会议,最后得到了答案。

答案是:

def destroy
#/assign_roles/9?user_id=27
    user = User.find_by_id(params[:user_id])
    assigned_role = Role.find(params[:id])
    organisation = Organisation.find(current_user.organisation)

    user.remove_role assigned_role.name.to_sym, current_user.organisation #user.organisation

    flash[:notice] = "role deleted"
    redirect_to root_path
  end

在视图中:

        <td><%= link_to 'Remove role', assign_role_path(role, user_id: user),  method: :delete, data: { confirm: 'Are you sure?' } %></td>

具体问题是角色名称在被删除之前需要转换为字符串,而用户查找方法正在最近的资源中搜索(这意味着它在角色模型中寻找id,而不是用户模型。这意味着id将无法返回用户ID。我不理解这部分rails的搜索结构 - 所以我必须把它当作给定(不理解它),但非常高兴,经过多年试图解决这个问题,我可以继续前进。