Reputation: 63
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:
MODEL
def self.calculate(from_date,to_date)
days = 0
date_1 = Date.parse(from_date)
date 2 = Date.parse(to_date)
days = date_1.business_days_until(date2)
days
end
CONTROLLER
def new
@vacation = current_user.vacations.build
@vacations = Vacation.calculate(:from_date, :to_date)
end
I got an error referencing something about a string.
Furthermore, how do I go about storing the data from the method into the field called "credit"?
Thanks guys.
Upvotes: 0
Views: 43
Reputation: 106782
I think there is no need for an extra method, since all attributes (from_date
, end_date
and credit
) are stored in the same model.
I would just set from_date
and 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
Upvotes: 1
Reputation: 4322
What you need here is pass String
objects instead of Symbol
objects.
So instead of @vacations = Vacation.calculate(:from_date, :to_date)
, you probably need to pass params[:from_date]
and params[:to_date]
which should be strings like 20/01/2016
, etc...
Your code should be
@vacations = Vacation.calculate(params[:from_date], params[:to_date])
Upvotes: 1