AlexNikolaev94 AlexNikolaev94 - 4 months ago 10
Ruby Question

Checkbox "NoMethodError" in rails

I'm writing a CMS and I faced a problem while making a role management for users. I have a boolean field

:admin
in my
User
model, and I've made a checkbox in my form to set created user as an administrator. Here is the
users_controller
:

def create
@user = User.create(user_params)
respond_to do |format|
if @user.save
format.html { redirect_to users_path }
format.json { head :no_content }
else
format.html { render :new }
format.json { render @user.errors, status: :unprocessable_entity }
end
end
end

def edit
end

def update
respond_to do |format|
if @user.update(user_params)
format.html { redirect_to users_path }
format.json { head :no_content }
else
format.html { render :edit }
format.json { render @user.errors, status: :unprocessable_entity }
end
end
end


and this is my form :

<%= form_for @user do |f| %>
# Here go fields for username, email and password
<p>
<%= f.label "Set as administrator" %> <br />
<%= f.hidden_field :admin, '' %>
# I also tried with <%= f.hidden_field :admin, false %>
<%= f.check_box :admin, checked = true %>
# Or <%= f.check_box :admin, data: { switch: true } %>
</p>
<% end %>


But any of these options returns me the following:

NoMethodError in Multiflora::Users#edit

undefined method `merge' for "":String


What have I done wrong?

Answer

Take hidden field as

<%= f.hidden_field :admin, value: '' %>,

or simply

<%= f.hidden_field :admin %>

and checkbox as <%= f.check_box :admin, :checked => true %>

<%= form_for @user do |f| %>
  # Here go fields for username, email and password
  <p>
    <%= f.label "Set as administrator" %> <br />
    <%= f.hidden_field :admin, value: '' %>/<%= f.hidden_field :admin %> 
    <%= f.check_box :admin, :checked => true %> 
  </p>
<% end %>