向用户添加授权角色

时间:2015-08-24 00:05:53

标签: ruby-on-rails sql-update authorization roles

我希望能够作为管理员将授权角色添加到其他用户..当我单击添加角色按钮时,它表示它已将角色添加到该用户..但是当我在Rails控制台中检查角色时该用户仍然是零。

def index
    @user = User.new
    @users = User.all
end

def update
    @users = User.all
    @user = User.find_by_username(params[:user][:username])
    if @user && params[:user][:role] == "editor"
        @user.role = "editor"
        @user.save
        flash.notice = "Added role 'editor' to #{@user.username}."
        redirect_to "/adminsettings"
    elsif @user && params[:user][:role] == "admin"
        @user.role = "editor"
        @user.save
        flash.notice = "Added role 'editor' to #{@user.username}."
        redirect_to "/adminsettings"
    elsif @user && params[:user][:role] != "editor"
        flash.notice = "Please chose 'editor' if you want to add this role to this user."
        redirect_to "/adminsettings"
    else
        redirect_to "/adminsettings"
        flash.notice = "Please choose one of the users below."
    end
end 

查看

<%= form_for @user ,:url => {:controller => "admin_settings", :action => "update"}, method: :patch do |user| %>
    <%= user.text_field :username, :placeholder => "Username" %><br />
    <%= user.text_field :role, :placeholder => "Role" %><br />
    <%= user.submit "Add Role" %>
<% end %>

<% @users.each do |user| %>
    <strong><%= user.username %></strong><br />
<% end %>

路线

  get '/adminsettings', to: 'admin_settings#index'
  patch '/adminsettings', to: 'admin_settings#update'

1 个答案:

答案 0 :(得分:0)

尝试将调用params的用法更改为此...

def update
    @users = User.all
    @user = User.find_by_username(params[:username])
    if @user && params[:role] == "editor"
        @user.role = "editor"
        @user.save
        flash.notice = "Added role 'editor' to #{@user.username}."
        redirect_to "/adminsettings"
    elsif @user && params[:role] == "admin"
        @user.role = "editor"
        @user.save
        flash.notice = "Added role 'editor' to #{@user.username}."
        redirect_to "/adminsettings"
    elsif @user && params[:role] != "editor"
        flash.notice = "Please chose 'editor' if you want to add this role to this user."
        redirect_to "/adminsettings"
    else
        redirect_to "/adminsettings"
        flash.notice = "Please choose one of the users below."
    end
end