我是 Ruby on Rails 新手,我正在使用 Ruby 1.9.3 和 Rails 4.0.2。
如何在不使用 devise 的情况下添加新的管理员用户?
我正在使用下面的代码并提交添加新用户表单,其中数据admin_user_params
返回空白,并且在数据库中插入一条空白记录。
这是我的用户数据库表
create_table :users do |t|
t.integer :role_id
t.string :name
t.string :email
t.string :username
t.string :encrypted_password
t.string :reset_password_token
t.string :is_status
t.string :is_active
t.integer :sign_in_count
t.string :current_sign_in_ip
t.string :last_sign_in_ip
t.string :authentication_token
t.datetime :reset_password_sent_at
t.datetime :remember_created_at
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
这是我的 Controller
class Admin::UsersController < ApplicationController
before_action :set_admin_user, only: [:show, :edit, :update, :destroy]
def new
@admin_user = User.new
end
def create
#@admin_user = Admin::User.new(admin_user_params)
@admin_user = User.new(admin_user_params)
respond_to do |format|
if @admin_user.save
format.html { redirect_to @admin_user, notice: 'User was successfully created.' }
format.json { render action: 'show', status: :created, location: @admin_user }
else
format.html { render action: 'new' }
format.json { render json: @admin_user.errors, status: :unprocessable_entity }
end
end
end
end
*这是我的用户模型*
注意:
我不想创建 admin_user 模型。我只想对管理区域和前台区域使用用户模型。
class User < ActiveRecord::Base
#Setup accessible (or protected) attributes for your model
attr_accessible :name, :username, :role_id, :email, :password, :password_confirmation, :remember_me, :id, :admin_permission
attr_accessor :password, :new_password, :previous_email, :previous_username, :remember_me
belongs_to :role
def super_admin?
self.role.name == "Super Admin"
end
end
这是我的观点
<%= form_for [:admin,@admin_user] do |f| %>
<% if @admin_user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@admin_user.errors.count, "error") %> prohibited this admin_user from being saved:</h2>
<ul>
<% @admin_user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :Name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :Email %><br>
<%= f.text_field :email %>
</div>
<div class="field">
<%= f.label :Username %><br>
<%= f.text_field :username %>
</div>
<div class="field">
<%= f.label :Password %><br>
<%= f.text_field :encrypted_password %>
</div>
<div class="actions">
<p><%= f.submit 'Sign up' %></p>
</div>
<% end %>
请帮忙。
最佳答案
我认为添加管理员用户功能的最简单方法是向您的 users
表添加 bool admin
行。
然后,在您的 Controller 中,您可以使用 before_action
控制对特定操作的访问,以确保用户是管理员,或者重定向到 root_url
(或其他位置) 。
您还可以通过在条件中调用 User#admin?
有选择地查看 View 中的元素。
不确定这是否满足您的需求,但希望对您有所帮助。
关于ruby-on-rails - 如何在 Ruby on Rails 中不使用 devise 添加新的管理员用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20964131/