Pretty new to RoR. Wonder if anyone can help me with this issue.
I got a gem called "business_time" which calculates the business days between two dates. I have set up a method in the model which does all the calculations.
I have a field called "credit" which should hold the number of business days. Here's what I have:
days = 0
date_1 = Date.parse(from_date)
date 2 = Date.parse(to_date)
days = date_1.business_days_until(date2)
@vacation = current_user.vacations.build
@vacations = Vacation.calculate(:from_date, :to_date)
I think there is no need for an extra method, since all attributes (
credit) are stored in the same model.
I would just set
end_date in the initializer and calculate
credit with a callback before validation:
# in the model before_validation :calculate_credit private def calculate_credit if from_date && to_date # `+ 1` because the user takes off both days (`from_date` and `to_date`), # but `business_days_until` doesn't count the `from_day`. self.credit = from_date.business_days_until(to_date) + 1 end end # in the controller def new @vacation = current_user.vacations.build end def create @vacation = current_user.vacations.build(vacation_params) if @vacation.save # @vacation.credit would return the calculated credit at this point else # ... end end private def vacation_params params.require(:vacation).permit(:from_date, :to_date) end