2012-01-13 71 views
4

我在用户设置中显示或隐藏用户配置文件的一部分。该表单是一个,当它被点击时,我使用jQuery来提交表单。这一切都很好。点击复选框将布尔值从true切换到false,反之亦然。不过,我希望复选框显示为检查我的布尔值是否为false。下面给出我的代码,我该怎么做?如果布尔值为false,则复选框呈现为选中状态

我的控制器操作的配置文件的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(); 
    }); 
}); 

回答

10

我有人对你的逻辑感到困惑,但我想你明白了。只要你需要他们就改变真假。如果@ user.profile.hometown设置为false,这会将复选框设置为选中状态。

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

我其实希望勾选“@ user.profile.show_hometown”为false。另外,作为一个初学者,我很好奇我的逻辑是什么让你感到困惑,以及如何让它变得更好。 – tvalent2 2012-01-14 01:44:34

+0

这实际上工作。出于某种原因,它一开始并没有,但后来就奏效了。尽管如此,我仍然对好奇心很感兴趣。谢谢!如您所知, – tvalent2 2012-01-14 04:46:58

+0

check_box_tag会创建一个html复选框。有3个参数给出: – 2012-01-14 16:40:27

相关问题