[英]How to set simple_form input default value
= r.input :date_start do
= r.text_field :date_start, id: 'date_start'
如何为此设置默认值?
= r.input :date_start, as: :string, input_html: {value: '01/01/2015', id: 'date_start'}
使用此代码:
= r.input :date_start, as: :string, input_html: {id: 'date_start',value: '07/02/2015'}
使用安全导航或&.
在this Answer to another question中解释,这里是一个选项; 特别是当与||
链接时操作员。
注意:我使用的是Time.now
而不是Time.new
,因为我觉得它更具可读性,并且更好地传达了默认值的意图。 如果您想查看有关 now 和 new 的对话或基准,我推荐这个Question 。 在这个答案中,也有一个很好的解释,说明为什么您可能想要使用Time.current
代替)
input_html: { value: (f.object.date_start.present?) ? f.object.date_start : Time.now }
与此对重复问题的回答相同,无需解释,以上可以改写为:
input_html: { value: f.object&.date_start || Time.now }
如果存在,则提供现有值,如果不存在,则提供 nil。 与||
配对时运算符,逻辑查找第一个“真实”响应。 nil
不被认为是“真实的”,而||
在这种情况下,将选择默认值而不是nil
或Time.now
。
最后,我觉得这是为一个简单的表单输入设置默认值的可读性和更少冗余的答案。
= f.input :date_start, input_html: { value: f.object&.date_start || Time.now }
我重构 Kiry's Answer 的另一个原因是因为我认为在这种情况下使用三元组接近违反Tell, Don't Ask的原则,如示例 4 所示: Tell, Don't Ask: refactoring examples .
Gavit的答案的解释是在保存记录的迁移中设置默认值:
# migration
class AddDefaultToDateStartOfObj < ActiveRecord::Migration[5.2]
def change
change_column :objs, :date_start, -> { 'CURRENT_TIMESTAMP' }
end
end
# simple_form input
= f.input :date_start
注意:根据您的数据库类型,SQL 可能会有所不同,但这里有一个关于此迁移细微差别的好问题。
但是,当对象是新的并且不是数据库中的记录时,这不起作用。
我推荐迁移以及在对象模型中构建一个处理默认输入的方法会更清晰/更具可读性,同时遵循更好的编码原则。
# simple_form input
= f.input :date_start, input_html: { value: f.object.date_start_with_default }
# Model with date_start attribute
class Obj
def date_start_with_default
# based on your model, like in Kiry's comment to their own answer, you may need this instead:
# try(:date_start) || Time.now
date_start || Time.now
end
end
现在,可以通过模型在一个地方控制/更新默认此值的所有逻辑。
尝试这个:
= f.input :date_start, input_html: { value: (f.object.date_start.present?) ? f.object.date_start : Time.new }
在数据库中指定它: t.date : date_start, :null => false, :default => 'now()'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.