Default value for input with simple_form

一个人想着一个人 提交于 2019-12-03 08:03:52

问题


im trying to do default value for input

works ok:

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

but i need f.input not f.input_field

<%= f.input :quantity %> 


  • im trying it with standard html value - but after unsucessfull validation quantity is overriden by 1 - undesired

    <%= f.input :quantity, input_html: {value: '1'} %>
    
  • when i remove value and validation is unsucessfull quantity is populated - everything is ok

    <%= f.input :quantity %>
    

how to solve this ? is there any alternative like in f.input_field - :default ? or there is any other solution with value ?


回答1:


You can try with something like this:

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



回答2:


You can use the selected option of simple_form: <%= f.input :quantity, selected: f.object.quantity || '1' %>




回答3:


try this:

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



回答4:


This is an old question...but, none of provided answers seem acceptable to me. The best way to do this is to set the value in the controllers new action.

 def new
   WizBang.new(quantity: 1)

This will assign the objects quantity key to value 1 in the new action. The edit action should rely on the object's persisted value, or a params value if validation failed and the form reloaded. The other answers will force the quantity to 1 on edit, even if the user initially saved nil (if you allow nil). Not ok. I would not allow nil, but would include a 0 option in the quantity field.

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

much cleaner.




回答5:


You can do

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

Nowadays, leaving off the input_html key.



来源:https://stackoverflow.com/questions/19029129/default-value-for-input-with-simple-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!