Keeping dates in order when using date_select and discarding year in Rails?
- by MikeH
My app has users who have seasonal products. When a user selects a product, we allow him to also select the product's season. We accomplish this by letting him select a start date and an end date for each product.
We're using date_select to generate two sets of drop-downs: one for the start date and one for the end date.
Including years doesn't make sense for our model. So we're using the option: discard_year => true
To explain our problem, consider that our products are apples. Vendor X carries apples every year from September to January. Years are irrelevant here, and that's why we're using discard_year => true. However, while the specific years are irrelevant, the relative point in time from the start date to the end date is relevant. This is where our problem arises.
When you use discard_year => true, Rails does set a year in the database, it just doesn't appear in the views. Rails sets all the years to 0001 in our app. Going back to our apple example, this means that the database now thinks the user has selected September 0001 to January 0001. This is a problem for us for a number of reasons.
To solve this, the logic that I need to implement is the following:
- If season_start month/date is before season_end month/date, then standard Rails approach is fine.
- But, if season_start month/date is AFTER season_end month/date, then I need to dynamically update the database field such that the year for season_end is equal to the year for season_start + 1.
My best guess is that I would create a custom method that runs as an after_save or after_update in my products model. But I'm not really sure how to do this.
Ideas? Anybody ever had this issue? Thanks!