user1175969
user1175969

Reputation: 570

Set default value of date_field only if current value is empty

I'm using the same form in a partial to both create a new object and modify it. I have the following field:

<%= f.date_field :dob, class: 'form-control' %>

I know that I can set its default by adding value: Time.now.strftime('%Y-%m-%d'), but I want to do this if and only if the current value is empty. How do I do that?

Upvotes: 2

Views: 1755

Answers (2)

Kumar
Kumar

Reputation: 3126

You can directly check if its nil, and provide today's date.

Lets say the form is for @person

<%= f.date_field :dob, value: @person.dob || Date.today.strftime("%Y-%m-%d"), class: "form-control" %>

Upvotes: 2

Hardik Upadhyay
Hardik Upadhyay

Reputation: 2659

suppose, this form for user then,

<% date = @user.dob.present? ? @user.dob : Time.now.strftime('%Y-%m-%d') %>

<%= f.date_field :dob, value: date, class: 'form-control' %>

Hope this will help you.

Upvotes: 1

Related Questions