Hieu Ha
Hieu Ha

Reputation: 23

Set default for a datetime attribute in simple form

I want to pre-assign 1448607600 (=2015-11-27 07:00:00 +0000) to a datetime attribute called starts_at in a simple_form. I did the following but didn't work. Pls help!

<%= f.input :starts_at, input_html: { value: Time.at(1448607600) } %>

I also did the following but no luck:

<%= f.input :starts_at, input_html: { value: Time.at(1448607600).to_s.to_datetime) } %>

Upvotes: 0

Views: 2547

Answers (2)

bosskovic
bosskovic

Reputation: 2054

It would be much better if you assigned the default date in the conroller as @Mareq suggested in the comment, but you could also do it with a callback in the model

Assuming that you have a model named Resource, in controller you could do this:

@my_object = Resource.new
@my_object.starts_at = Time.at(1448607600)

Or in the model you could have this:

DEFAULT_TIME = 1448607600.freeze
after_initialize :set_default_time, :if => :new_record?

private
def set_default_time
  self.starts_at = Time.at(DEFAULT_TIME)
end

In both cases in the new view you would have something like this:

<%= simple_form_for @my_object do |f| %>
  <%= f.input :starts_at %>
<% end %>

Upvotes: 1

scottysmalls
scottysmalls

Reputation: 1251

Not sure which errors you are getting, but DateTime.strptime function should get you a valid DateTime object that you can format how you like

<%= f.input :starts_at, input_html: { value: DateTime.strptime("1448607600",'%s').to_s } %>

Upvotes: 0

Related Questions