'Stoping rails from going back in time when booking?
I made this simple form and I don't want to book back in time. Is there any command which fixes the problem?
<div class="container">
<div class="row justify-content-center align-items-center">
<div class="col">
<div class="booking-card p-5 mt-5">
<h1>Create a new booking!</h1>
<%= simple_form_for [@listing, @booking] do |f| %>
<%= f.input :start_date %>
<%= f.input :end_date %>
<div class="form-actions">
<%= f.button :submit, "Create booking", class:"button-28" %>
</div>
<% end %>
</div>
</div>
</div>
</div>
Solution 1:[1]
I agree with the above answer that you should add a Model validation to prevent the database from saving dates in the past.
I see you are using the SimpleForm gem, and they probably have a similar option to the built-in Rails helper.
If you want to add a slightly better user experience, I recommend using a Datetime form field. Rails has lots of built-in Form Helpers, including one to select a Date input.
With this helper, you can set the minimum valid date, so you can prevent users from inputting dates in the past/"back in time".
# Example with Rails FormHelper
<%= form_for [@listing, @booking] do |f| %>
<%= f.date_field :start_date, min: Date.today %>
<%= f.date_field :end_date %>
<div class="form-actions">
<%= f.submit "Create booking", class:"button-28" %>
</div>
<% end %>
Solution 2:[2]
You need to add validation to the booking model.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sassyg |
| Solution 2 | Kamil Gwó?d? |
