Check the box to render as checked if boolean is false

I have a form working in user settings to show or hide part of the user profile. The form is check_box_tag , and when it is clicked, I use jQuery to submit the form. It all works well. Clicking on a checkmark toggles the boolean value from true to false or vice versa. However, I would like the checkbox to show as checked if my boolean value is false . How to do this, given my code below?

My controller action for update_attribute profile:

 def edit_show_hometown_settings @profile = current_user.profile if @profile.show_hometown == true if @profile.update_attributes(:show_hometown => false) redirect_to settings_path else redirect_to settings_path, :notice => 'Oops, something went wrong. Please try again.' end elsif @profile.show_hometown == false if @profile.update_attributes(:show_hometown => true) redirect_to settings_path else redirect_to settings_path, :notice => 'Oops, something went wrong. Please try again.' end end end 

My form:

 <%= form_tag({:action => "edit_show_hometown_settings", :controller => "profiles"}, :html => {:multipart => true }) do %> <%= check_box_tag :show_hometown %> <%= @user.profile.hometown %> <% end %> 

jQuery which I use to submit the form:

 $(function(){ $(':checkbox').live('click',function() { $(this).closest('form').submit(); }); }); 
+4
source share
1 answer

I'm a little confused by your logic, but I think you get the point. Just change the truth and the lie when you need them. This will check the box if @ user.profile.hometown is set to false.

 <%= check_box_tag :show_hometown , 1 , @user.profile.hometown ? false : true %> 
+10
source

Source: https://habr.com/ru/post/1390770/


All Articles