【问题标题】:Get checkbox to render as checked if boolean value is false如果布尔值为 false,则获取复选框以呈现为选中状态
【发布时间】:2012-01-13 17:07:35
【问题描述】:

我的用户设置中有一个表单,用于显示或隐藏用户个人资料的一部分。表单是check_box_tag,当它被点击时,我使用 jQuery 提交表单。这一切都运作良好。单击复选框将布尔值从true 切换到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();
    });
});

【问题讨论】:

    标签: ruby-on-rails-3 checkbox


    【解决方案1】:

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

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

    【讨论】:

    • 如果@user.profile.show_hometown 为假,我实际上希望选中复选框。另外,作为一个初学者,我很好奇你对我的逻辑有什么困惑,以及我怎样才能使它变得更好。
    • 这确实有效。出于某种原因,它一开始并没有,但后来它起作用了。不过我还是很好奇其中的逻辑。谢谢!
    • check_box_tag 创建一个 html 复选框,如您所知。给出了 3 个参数:
    • 第一个将name属性设置为“show_hometown”,第二个将复选框的值设置为“1”,第三个是一个布尔值,用于确定该框是否被选中-如果给定的值为真,则检查它。由于您希望检查您的框,因此当值为假时,您必须反转您的@user.profile.hometown 值。我使用三元运算符做到了。实际上你可以也只需将“!@user.profile.hometown”作为第三个参数传递......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多