【发布时间】:2013-08-04 05:12:48
【问题描述】:
我正在使用 Devise 和 CanCan 使用 Rails 4 构建应用程序。当新用户注册时,他们不会被赋予默认角色。管理员必须通过管理面板手动分配它。这就是我遇到困难的地方。我不知道如何更新联接字段中的数据。这是我目前所拥有的。
我的用户控制器:
class UsersController < ApplicationController
before_filter :authenticate_user!
before_action :set_user, only: [:show, :update, :destroy]
def index
authorize! :index, @user, message: 'Not authorized as an administrator.'
@users = User.all
end
def show
end
def update
authorize! :update, @user, message: 'Not authorized as an administrator.'
if @user.update_attributes(user_params)
redirect_to users_path, notice: "User updated."
else
redirect_to users_path, alert: "Unable to update user."
end
end
def destroy
authorize! :destroy, @user, message: 'Not authorized as an administrator.'
unless @user == current_user
@user.destroy
redirect_to users_path, notice: "User deleted."
else
redirect_to users_path, notice: "Can't delete yourself."
end
end
private
def set_user
@user = User.find(params[:id])
end
def user_params
params.require(:user).permit(:name, :email, :role_id, :user_id)
end
end
还有我的榜样:
class Role < ActiveRecord::Base
has_and_belongs_to_many :users, :join_table => :users_roles
belongs_to :resource, :polymorphic => true
scopify
end
还有我的用户模型:
class User < ActiveRecord::Base
rolify
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
如您所见,它几乎是 Devise 生成的标准模型。
这是我用来更新角色的表格:
<div id="role-options-<%= user.id %>" class="reveal-modal medium" style="display: none;">
<%= simple_form_for user, url: user_path(user), html: {method: :put, class: 'custom' } do |f| %>
<h3>Change Role</h3>
<%= f.input :role_ids, collection: Role.all, as: :radio_buttons, label_method: lambda {|t| t.name.titleize}, label: false, item_wrapper_class: 'inline', checked: user.role_ids.first %>
<%= f.submit "Change Role", class: "small button" %>
<a class="close-reveal-modal" href="#">Close</a>
<% end %>
</div>
当我检查表单上的新角色并提交时,我被重定向到用户页面,并显示“用户已更新”消息。但是,用户角色尚未更新。
我对 Rails 还很陌生,只是无法弄清楚我做错了什么。如果我理解正确,我需要更新 user_roles 表中的数据。我就是想不通我做错了什么。
【问题讨论】:
-
可能,您应该将
UsersController#user_params更改为允许:role_ids -
一个用户可以拥有多少个角色?
-
@taro 加油!这就是问题所在。如果您将其作为答案提交,我很乐意选择它作为正确答案。
标签: ruby-on-rails ruby devise cancan