【问题标题】:Default value for input with simple_formsimple_form 输入的默认值
【发布时间】:2013-09-26 13:04:47
【问题描述】:

我正在尝试为输入设置默认值

工作正常:

<%= f.input_field :quantity, default: '1' %> 

但我需要 f.input 而不是 f.input_field

<%= f.input :quantity %> 


  • 我正在尝试使用标准 html 值 - 但在不成功的验证数量被 1 覆盖后 - 不需要

    <%= f.input :quantity, input_html: {value: '1'} %>
    
  • 当我删除值并且验证不成功时,填充数量 - 一切正常

    <%= f.input :quantity %>
    

如何解决这个问题? 有没有像 f.input_field - :default 这样的替代方法? 还是有其他有价值的解决方案?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 erb simple-form


    【解决方案1】:

    你可以试试这样的:

    <%= f.input :quantity, input_html: {value: f.object.quantity || '1'} %>
    

    【讨论】:

      【解决方案2】:

      您可以使用 simple_form 的 selected 选项: <%= f.input :quantity, selected: f.object.quantity || '1' %>

      【讨论】:

        【解决方案3】:

        试试这个:

        = f.input : quantity, input_html: { value: (f.object.quantity.present?) ? f.object.quantity : '1' }
        

        【讨论】:

        • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
        【解决方案4】:

        这是一个老问题......但是,我似乎没有接受任何提供的答案。最好的方法是在控制器的新操作中设置值。

         def new
           WizBang.new(quantity: 1)
        

        这会将对象数量键分配给新操作中的值 1。编辑操作应该依赖于对象的持久值,或者如果验证失败并且重新加载表单,则需要一个参数值。即使用户最初保存 nil(如果您允许 nil),其他答案也会在编辑时强制数量为 1。不好。我不允许 nil,但会在数量字段中包含一个 0 选项。

        f.input :quantity, collection (0..100)
        

        干净多了。

        【讨论】:

          【解决方案5】:

          你可以的

          <%= f.input :quantity, value: f.object.quantity || '1' %>
          

          现在,不用input_html 键。

          【讨论】:

            【解决方案6】:

            现在确定如何引用重复问题的答案,但我分享的是 Answer 我刚刚留下了一个我标记为重复的问题。

            以下是这个问题的摘要:

             # simple_form input
             f.input :quantity, input_html: {value: f.object.quantity || '1'}
            

            可以变成:

             # simple_form input
             = f.input :quantity, input_html: { value: f.object.quantity_with_default }
            
             # Model with date_start attribute
             class Obj
               def quantity_with_default
                 # based on your model, you may need this instead: try(:quantity) || '1' 
                 quantity || '1' 
               end
             end
            

            这将数据及其默认值的管理留在控制器中,而不是散布在整个 HTML 中

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-07-05
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多