我是Ruby on Rails的新手,我使用的是Ruby 1.9.3和Rails 4.0.2。如何在不使用Ruby on Rails的情況下添加新的管理用戶
如何在不使用設計的情況下添加新的管理員用戶?
我正在使用下面的代碼並提交添加數據的新用戶表單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
這是我的控制器
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 %>
請幫助。
從您的用戶模型中刪除attr_accessor並在attr_accessible中寫入屬性。 –
你有':admin_permission'作爲'attribute_acessible',但我沒有在你的表格設計中看到這個? 'admin_user_params'沒有分配給任何你會使用'params'哈希值的東西。如果您驗證模型中的記錄,這可能會變得更清晰。還有:id作爲可訪問的屬性會引起一些關注,因爲它可能允許僞造的更新請求來設置新的id。 – engineersmnky
對不起,只是想指出':role_id'的同一個問題。說'role_id 1' ='管理員角色'。假設你有一個表單,可以讓我更改電子郵件地址並使用標準的'update_attributes'方法。這將允許我攔截請求並向params散列中添加一個參數,該參數表示「role_id = 1」,並且當通過更新方法處理該請求時,我現在分配了一個「管理員角色」。如果你刪除了'attribute_accessible',那麼它將成爲'MassAssignment Error'。 – engineersmnky