自己周末在自学 Rails 开发,遇到了一个问题,特此请教大家。首先,问题情景是:我想在后台修改用户的权限,具体是 admin 字段,但是 form 中更改后出了问题。
我建的 User 表如下:
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# password_digest :string(255)
# remember_token :string(255)
# admin :boolean default(FALSE)
#
class User < ActiveRecord::Base
attr_accessor :current_password
attr_accessible :email, :name, :password, :password_confirmation, :current_password
has_secure_password
before_save { |user| user.email = email.downcase }
before_save :create_remember_token
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensetive: false }
validates :password, presence: true, length: { minimum: 6 }
validates :password_confirmation, presence: true
private
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
end
views 部分如下
<%= form_for([:manage, user]) do |f| %>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4>权限修改</h4>
</div>
<div class="modal-body">
<label>当前权限:</label>
<%= f.select :admin, options_for_select([['管理员', true], ['用户', false]], user.admin) %>
</div>
<div class="modal-footer">
<a class="btn btn-primary" data-dismiss="modal" aria-hidden="true">取消</a>
<%= f.submit "保存", class: "btn btn-primary", 'data-disable-with' =>"正在保存" %>
</div>
<% end %>
controller 部分如下:
class Manage::UsersController < Manage::ApplicationController
def index
@users = User.order(:id).page(params[:page])
end
def destroy
User.find(params[:id]).destroy
flash[:success] = "用户已被成功删除!"
redirect_to manage_users_url
end
def update
@user = User.find(params[:user])
if @user.update_attributes(params[:user])
flash[:success]="修改成功!"
redirect_to manage_users_url
else
redirect_to manage_users_url
end
end
end
我实际测试时,点击“保存”后页面提示错误,具体如下所示:
ArgumentError in Manage::UsersController#update
Unknown key: admin
Rails.root: /Users/huyipeng/Projects/cloud/xinyi
Application Trace | Framework Trace | Full Trace
app/controllers/manage/users_controller.rb:16:in `update'
Request
Parameters:
{"utf8"=>"✓",
"_method"=>"put",
"authenticity_token"=>"5eOB401SeJ4/T+EIfzYl5uG95rT4JhHCqIl5+ccpzgU=",
"user"=>{"admin"=>"true"},
"commit"=>"保存",
"id"=>"92"}
Show session dump
Show env dump
Response
Headers:
None
对于 admin 字段为什么会提示我说 unknown?是哪部分出现错误了吗?