2012-01-13 51 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

相關問題