0

I'm really struggling with what should be a fairly simple task

Before I had select_time and select_date and to separate the date and time but I can't figure out how to get it to a readable format to compare to Time.now.

I just want 2 validations, cannot start an event in the past, and cannot end an event before the start

In my form

<%= f.label :date_start %>
<%= f.datetime_select :date_start %>

In my event model

  validate :start_date_cannot_be_in_the_past

 def start_date_cannot_be_in_the_past

    date = Time.new(date_start(1i).to_i, date_start(2i).to_i, date_start(3i).to_i, date_start(4i).to_i, date_start(5i).to_i)
    if date < Time.now
      errors.add(:date_start, "has already passed")
    end
  end

Date + time selectors all break down values like this

 "date_start(1i)"=>"2014",
 "date_start(2i)"=>"11",
 "date_start(3i)"=>"8",
 "date_start(4i)"=>"04",
 "date_start(5i)"=>"13"},
Clam
  • 935
  • 1
  • 12
  • 24
  • Why break it down? I myself am not familiar with datetime_select, but by logic it should provide a single datetime value. Why not simply compare that to DateTime.now? (rather than Time.now) `if date_start > DateTime.now` – Kasperi Nov 08 '14 at 04:26
  • I can try that but it doesn't seem to be validating properly still. I believe it's a timezone issue now.. If I do `Time.zone.now` I am getting my time in my time zone. But the `date_start` is entered in I'm guessing UTc time or something – Clam Nov 08 '14 at 04:57

1 Answers1

0

First you need Time.zone.now

second is a date attribute in the DB doing

 Model.new(params) 

should just set the date_start to the value in the form.

then in the model you do

def start_date_cannot_be_in_the_past
 if date_start_changed? # don't validate the value if the value didn't change.  Otherwise the record will not be valid after time passes
   errors.add(:date_start, "has already passed") if date_start < Time.zone.now
 end
 true # never return false or the validation fails
end
drhenner
  • 2,200
  • 18
  • 23
  • This doesn't seem to deal with the issue of date_start not being in the right time zone. I just tried this right now after looking at some time zone things. `date_time` seems to save in UTC time. How can I either convert that to local time zone or get Time.now into utc – Clam Nov 08 '14 at 05:04
  • Date time saves in UTC. Once you query for dates from the DB active record converts that time to your local APP time. That is just how AR works – drhenner Nov 08 '14 at 05:11
  • I've tried `Time.current.utc` like http://stackoverflow.com/questions/12748626/when-should-datetime-now-utc-vs-time-current-utc-be-used-in-rails with no luck :( – Clam Nov 08 '14 at 05:22