我有一个在用户设置中工作的表单,用于显示或隐藏用户个人资料的一部分。表单是一个check_box_tag
,单击它时,我使用jQuery提交表单。这一切都很好。单击复选框将 bool 值从true
切换到false
,反之亦然。但是,如果我的 bool 值是false
,我希望复选框显示为选中状态。给定下面的代码,我该怎么做?
我的 Controller 对Profile的update_attribute
的操作:
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
我的表格:
<%= form_tag({:action => "edit_show_hometown_settings", :controller => "profiles"}, :html => {:multipart => true }) do %>
<%= check_box_tag :show_hometown %>
<%= @user.profile.hometown %>
<% end %>
我用来提交表单的jQuery:
$(function(){
$(':checkbox').live('click',function() {
$(this).closest('form').submit();
});
});
最佳答案
我对您的逻辑感到困惑,但我想您明白了。只需根据需要更改对与错即可。如果@ user.profile.hometown设置为false,这会将复选框设置为选中。
<%= check_box_tag :show_hometown , 1 , @user.profile.hometown ? false : true %>