[英]Default value for input with simple_form
我试图为输入做默认值
工作正常:
<%= 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 那样的替代方法? 或者还有其他有价值的解决方案吗?
你可以尝试这样的事情:
<%= f.input :quantity, input_html: {value: f.object.quantity || '1'} %>
您可以使用 simple_form 的selected
选项: <%= f.input :quantity, selected: f.object.quantity || '1' %>
<%= f.input :quantity, selected: f.object.quantity || '1' %>
试试这个:
= f.input : quantity, input_html: { value: (f.object.quantity.present?) ? f.object.quantity : '1' }
这是一个老问题……但是,我似乎无法接受任何提供的答案。 最好的方法是在控制器新动作中设置值。
def new
WizBang.new(quantity: 1)
这将在新操作中将对象数量键分配给值 1。 如果验证失败并重新加载表单,则编辑操作应依赖于对象的持久值或参数值。 其他答案将在编辑时强制数量为 1,即使用户最初保存为 nil(如果您允许 nil)。 不行。 我不会允许 nil,但会在数量字段中包含一个 0 选项。
f.input :quantity, collection (0..100)
干净多了。
你可以做
<%= f.input :quantity, value: f.object.quantity || '1' %>
如今, input_html
键。
现在确定如何引用重复问题的答案,但我正在分享我刚刚在标记为重复的问题上留下的答案。
下面是这个问题的总结:
# 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 中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.