In my app there’s a user model with an admin role. I want admins to be able to create new admins, so on the users/edit page I’m hoping to create an admin-visible checkbox that, when checked turns the user into an admin. The code I’m using is here. Everything works other than the checkbox bit, which is why I’m asking. I’m new to Rails, and I just can’t figure out how to scrape the admin checkbox info and use it to alter the admin attribute (which is attr_protected for security reasons).
My edit form
<div class="row">
<div class="span6 offset3">
<%= form_for(@user) do |f| %>
<%= render 'shared/error_messages' %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.label :password_confirmation, "Confirmation" %>
<%= f.password_field :password_confirmation %>
<% if signed_in? %>
<% if current_user.admin? %>
<h3> Click to Switch On/Off Admin
<%= check_box_tag(:admin) %></h3>
<% end %>
<% end %>
<%= f.submit @string, class: "btn btn-large btn-primary" %>
<% end %>
</div>
</div>
The relevant lines of my user.rb file
before_save :toggle_admin
private
def toggle_admin
if self.admin == true
self.toggle!(:admin)
end
end
What am I doing wrong? It doesn’t toggle anything when I submit.
Thanks!
Sasha
Actually problem is because you had added :admin checkbox incorrectly. You have to do it like this:
It will produce input with correct name:
So then you will have correct params hash which is sent after form submission.
For additional details please check Rails documentation: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-check_box
Update #1
If in your case you want to use toggle for security reasons, just change
before_savetoafter_save, because toggle works like this:SQL output:
Update #2
In principle, you can implement it using a virtual attribute for checkbox.
Check tutorial about virtual attributes in Rails: http://railscasts.com/episodes/167-more-on-virtual-attributes