Keeping dates in order when using date_select and discarding year in Rails?
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/day is numerically before season_end month/day, then standard Rails approach is fine.
But, if season_start month/day is numerically AFTER season_end month/day, 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. For example, if a user selects October 15 to January 15, what he intends is October 15, 0001 to January 15, 0002. I need the app to reflect this.
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!
Add a before_save
callback in your Product
model.
class Product < ActiveRecord::Base
before_save :fix_end_date
def fix_end_date
self.end_date +=1.year if start_date > end_date
end
end
精彩评论