【问题标题】:Rails: User not being created with proper default roleRails:未使用正确的默认角色创建用户
【发布时间】:2016-10-23 18:02:00
【问题描述】:

在我的 rails 应用程序中,我只有两个角色,管理员和用户,我在架构和用户模型中定义了它们。这是我的带有用户表的 schema.rb:

  create_table "users", force: :cascade do |t|
    t.string   "first_name"
    t.string   "last_name"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    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.integer  "role",                   default: 2
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree

end

首先,这是我的用户模型:

class User < ActiveRecord::Base
    #Defining different roles
    enum role: [:Admin, :User]
    #Users can only have one scholarship application
    has_one :applications
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

我的能力模型:

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)
        if user.role = 1
            can :manage, :all
        elsif user.role = 2
            can :manage, Application
            can :manage, User
        else
            can :read, Static_Page
        end
    end
end

我的用户控制器:

class UsersController < ApplicationController
  before_action :authenticate_user
  #Users who are not signed in cannot view users list
  before_action :set_user, only: [:show, :edit, :update, :destroy]
  load_and_authorize_resource

  # GET /users
  # GET /users.json
  def index
    @users = User.all
  end

  # GET /users/1
  # GET /users/1.json
  def show
  end

  # GET /users/new
  def new
    @user = User.new
  end

  # GET /users/1/edit
  def edit
    @user = current_user
  end

  # POST /users
  # POST /users.json
  def create
    @user = User.new(user_params)

    respond_to do |format|
      if @user.save
        format.html { redirect_to @user, notice: 'User was successfully created.' }
        format.json { render :show, status: :created, location: @user }
      else
        format.html { render :new }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /users/1
  # PATCH/PUT /users/1.json
  def update
    respond_to do |format|
      if @user.update(user_params)
        format.html { redirect_to @user, notice: 'User was successfully updated.' }
        format.json { render :show, status: :ok, location: @user }
      else
        format.html { render :edit }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /users/1
  # DELETE /users/1.json
  def destroy
    @user.destroy
    respond_to do |format|
      format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:id])
    end

    #Never trust paramaters from the scary internet, man.
    def user_params
      params.require(:user).permit(:first_name, :last_name)
    end
end

在我看来,我添加了一些根据用户角色显示的条件,例如:

<% if user_signed_in? %>
<h4 class="center"> Welcome <%= current_user.first_name %>!</h4>
<% end %>
<% if user_signed_in? && current_user.role = "Admin" %>

<h4 class="center"> You are a <%= current_user.role %>, you can view all applications, edit them, delete users, and more!!</h4>
<% elsif user_signed_in? && current_user.role = "User" %>
<h4 class="center"> Thank you for your interest in our scholarship. As a <%= current_user.role %>, you may create, edit, or delete your scholarship application now that you are signed in.</h4>

<% else %>
<h4 class="center"> Welcome to the Philanthropist's Scholarship Application! Please create an account to apply for our scholarship!</h4>

<% end %>

我在我的用户视图中为管理员 CP(对于管理员)和帐户设置(对于用户)视图遵循了上述逻辑 - 以便管理员 CP 将显示所有用户,如用户的默认 rails 脚手架,而帐户设置只会显示当前用户的用户信息。

唯一的问题是,当我创建一个新用户时,它总是说用户是管理员,我创建了一个新用户,并且角色值似乎不等于 2(“用户”),他们只是一个管理员,可以做任何事情。

有什么建议吗?

【问题讨论】:

    标签: ruby-on-rails model-view-controller devise cancancan


    【解决方案1】:

    您需要在视图中使用 == not = 才能获得正确的功能。除此之外,您的用户表中的字段是一个整数......

    t.integer  "role",                   default: 2
    
    <% if user_signed_in? %>
    <h4 class="center"> Welcome <%= current_user.first_name %>!</h4>
    <% end %>
    <% if user_signed_in? && current_user.role == 1 %>
    
    <h4 class="center"> You are a <%= current_user.role %>, you can view all applications, edit them, delete users, and more!!</h4>
    <% elsif user_signed_in? && current_user.role == 2 %>
    <h4 class="center"> Thank you for your interest in our scholarship. As a <%= current_user.role %>, you may create, edit, or delete your scholarship application now that you are signed in.</h4>
    
    <% else %>
    <h4 class="center"> Welcome to the Philanthropist's Scholarship Application! Please create an account to apply for our scholarship!</h4>
    
    <% end %>
    

    【讨论】:

    • 您可以根据 current_user.role == 1 使用帮助方法来打印管理员或用户。将为您整理帮助并编辑帖子 - 目前从我所看到的你是一个,将根据他们的角色编号得到一个编号
    • 嗨,戴夫,感谢您的回复。我昨晚设法解决了这个问题 - 我还错过了另一个关键点,我有枚举角色:[:Admin,:User] 但后来我将架构中的角色设置为 2 - 但我没有设置为 2,因为它是 0 索引,比如 admin = 0 和 user 是 1。所以,我做了它 :Guest, :User, :Admin 并将默认值设置为 1。谢谢!
    • 不客气!很高兴你把它整理好了,当一切正常时,它总是一种邪恶的感觉!
    猜你喜欢
    • 2012-07-03
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    • 2011-10-08
    相关资源
    最近更新 更多