如何在Rails中的date_select帮助器中设置默认日期 [英] How to set default date in date_select helper in Rails
问题描述
<%= f.date_select:date_of_birth,:start_year => Time.now.year - 110,:end_year => Time.now.year%>
这将生成一个功能完整的日期字段集,工作正常但.... >
他们默认为今天不适合出生日期的日期(我不知道是什么,但除非你在运行新生儿单位今天的日期似乎不太理想)。我想要2010年1月1日(或2011年或任何一年恰好是)阅读。使用:默认选项已被证明不成功。我尝试了许多可能性,包括:
<%= f.date_select:date_of_birth,:default => {:year => Time.now.year,:month => 'Jan',:day => 1},:start_year => Time.now.year - 110,:end_year => Time.now.year%>
和
<%= f.date_select:date_of_birth,:default => Time.local(2010,'Jan',1),:start_year => Time.now.year - 110,:end_year => Time.now.year%>
这些都不会改变第一个例子的行为。默认选项是否按照描述进行工作?看来这应该是一个相当直接的事情。
Ta。
我认为最简单的方法是将它分配给控制器,例如新操作:
@person = Person.new(:date_of_birth =>2010-01-01.to_date)
然后在您的意见将获得正确的日期。
编辑:
如果要在模型级别分配默认值,可以尝试使用<一个href =http://blog.phusion.nl/2008/10/03/47/ =noreferrer>插件。但是我没有尝试过。
I'm trying to set up a date of birth helper in my Rails app (2.3.5). At present it is like so.
<%= f.date_select :date_of_birth, :start_year => Time.now.year - 110, :end_year => Time.now.year %>
This generates a perfectly functional set of date fields that work just fine but....
They default to today's date which is not ideal for a date of birth field (I'm not sure what is but unless you're running a neonatal unit today's date seems less than ideal). I want it to read Jan 1 2010 instead (or 2011 or whatever year it happens to be). Using the :default option has proven unsuccessful. I've tried many possibilities including;
<%= f.date_select :date_of_birth, :default => {:year => Time.now.year, :month => 'Jan', :day => 1}, :start_year => Time.now.year - 110, :end_year => Time.now.year %>
and
<%= f.date_select :date_of_birth, :default => Time.local(2010,'Jan',1), :start_year => Time.now.year - 110, :end_year => Time.now.year %>
None of this changes the behaviour of the first example. Does the default option actually work as described? It seems that this should be a fairly straightforward thing to do.
Ta.
I think that easiest way is to assign it in controller, for example for new action:
@person = Person.new(:date_of_birth => "2010-01-01".to_date)
Then in your view you will get correct date.
EDIT:
If you want to assign default value on model level, you can try do it with plugin. However I haven't try it.
这篇关于如何在Rails中的date_select帮助器中设置默认日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!