I'm separating a datetime column (which yes, I've named 'datetime'... maybe that's too confusing) into two virtual attributes, date_field
and time_field
.
Then using this SO answer I'm recombining the two in a before_save
callback.
However, now validation always fails with "can't be blank" whether or not I've filled in the date_field
or time_field
Here's my model:
class SomeModel < ActiveRecord::Base
validates :date_field, :time_field, presence: true
before_save :convert_to_datetime
def date_field
datetime.strftime("%d/%m/%Y") if datetime.present?
end
def time_field
datetime.strftime("%I:%M%p") if datetime.present?
end
def date_field=(date)
@date_field = Date.parse(date).strftime("%Y-%m-%d")
end
def time_field=(time)
@time_field = Time.parse(time).strftime("%H:%M:%S")
end
def convert_to_datetime
self.datetime = DateTime.parse("#{@date_field} #{@time_field}")
end
end
Edit:
Here's a little new information after investigation:
1) Per xmpolaris's comment, I tried @date_field || datetime.present? datetime.strftime("%d/%m/%Y") : nil
, but that returns nil
2) I replaced before_save
with before_validation
and that gave me a 500 invalid date error.
3) I've inspected the params with byebug and they look like this:
(byebug) p params[:date_field]
"2014-02-10"
(byebug) p params[:time_field]
"11:30"
Is that the correct format for Rails?