简体   繁体   中英

Rails Validating date_select and time_select

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"},

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM