Ruby on rails 3 如果布尔值为false,则获取复选框以显示为选中状态

Ruby on rails 3 如果布尔值为false,则获取复选框以显示为选中状态,ruby-on-rails-3,checkbox,Ruby On Rails 3,Checkbox,我有一个在我的用户设置中工作的表单,用于显示或隐藏用户配置文件的一部分。表单是一个复选框标记,单击它时,我使用jQuery提交表单。这一切都很好。单击复选框可将布尔值从true切换到false,反之亦然。但是,如果布尔值为false,我希望复选框显示为选中。鉴于下面的代码,我该如何做 我的控制器对配置文件的更新\u属性的操作: def edit_show_hometown_settings @profile = current_user.profile if @profile.show_

我有一个在我的用户设置中工作的表单,用于显示或隐藏用户配置文件的一部分。表单是一个
复选框标记
,单击它时,我使用jQuery提交表单。这一切都很好。单击复选框可将布尔值从
true
切换到
false
,反之亦然。但是,如果布尔值为
false
,我希望复选框显示为选中。鉴于下面的代码,我该如何做

我的控制器对配置文件的
更新\u属性的操作:

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 %>

我对你的逻辑有点困惑,但我想你明白了。只要根据需要改变真假。如果@user.profile.homely设置为false,则此操作将复选框设置为选中

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


如果
@user.profile.show\u
为false,我实际上希望选中该复选框。另外,作为一个初学者,我很好奇我的逻辑你对什么感到困惑,以及我如何使它更好。实际上,这是有效的。由于某种原因,它起初没有成功,但后来成功了。不过,我仍然对逻辑感到好奇。谢谢正如您所知,check_-box_标记创建了一个html复选框。给出了3个参数:第一个参数将name属性设置为“show_homely”,第二个参数将复选框的值设置为“1”“选中时,第三个是一个bolean值,用于确定框是否选中-是否选中,给定的值是否为真。”。由于您希望复选框被选中,因此当值为false时,您必须反转@user.profile.homerium值。我用了三元运算符。实际上,您也可以将“!@user.profile.homely”作为第三个参数传递。。。
<%= check_box_tag :show_hometown , 1 , @user.profile.hometown ? false : true %>