I have created a boolean on devise User to determine admins. Now that I have that, I have a list of Users. I want to make other users admins as well, so I put in Edit links, but they just keep linking to my own profile. Do I HAVE to use a gem like CanCan, or is there a way I can do this just with the boolean on a User?
admin_view.html.erb
<div>
<h1>Admin View</h1>
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Native Language</th>
<th>Learning Language</th>
<th>Admin?</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @users.each do |user| %>
<tr>
<td><%= user.first_name %></td>
<td><%= user.last_name %></td>
<td><%#= user.meeting_time %></td>
<td><%= user.admin %></td>
<td><%= %></td>
<td><%= %></td>
<td><%= link_to 'Edit', edit_user_path(user) %></td>
<% end %>
</tr>
</tbody>
</table>
edit view
<h2>Edit <%= resource_name.to_s.humanize %></h2>
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
<%= devise_error_messages! %>
<div class="field">
<%= f.label :first_name %>
<%= f.text_field :first_name, autofocus: true %>
</div>
<div class="field">
<%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br />
<%= f.password_field :current_password, autocomplete: "off" %>
</div>
<div class="form-group">
<%= f.label :admin %>
<%= f.check_box :admin %>
</div>
<div class="actions">
<%= f.submit "Update" %>
</div>
<% end %>
Still very new to rails, so please let me know if I need to post anything else. Thanks!
UPDATE
profiler_controller.rb
def admin_view
@users = User.all
end
This is a case for authorization
(whether a user has permission).
As you've rightly stated, you can use CanCanCan
( CanCan
is no longer maintained) to do this, although there are many similar gems such as Pundit
etc.
If using CanCanCan
, I would use the following:
#config/routes.rb
resources :users do
post :admin #-> url.com/users/:user_id/admin
end
#app/models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.admin?
can :manage, :user
end
end
end
This will allow you to use:
#app/views/admin/users/index.html.erb
<% @users.each do |user| %>
<tr>
<td><%= user.first_name %></td>
<td><%= user.last_name %></td>
<td><%= user.admin %></td>
<td><%= link_to "Admin?", user_admin_path(user), method: :post if can? :manage, user %></td>
<td><%= link_to 'Edit', edit_user_path(user) %></td>
</tr>
<% end %>
#app/controllers/users_controller.rb
class UsersController < ApplicationController
def admin
@user = User.find params[:user_id]
@user.toggle :admin if can? :manage, @user
redirect_to @user
end
end
I can provide more if required; this should answer your question though.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.