1

A little new to Rails here so really appreciate all the help!

I have a form where I get the user to input 2 date fields. I want to calculate the number of days between these 2 dates. How would I go about doing this? Do I create a new method in the controller to calculate this?

Also, after I calculate this number, I want to display a new form x number of times (x = the calculated number of days). Any direction on how to do this would be great! Thanks in advance!

gitastic
  • 516
  • 7
  • 26
  • Possible duplicate of [Count number of days between two dates](http://stackoverflow.com/questions/9572860/count-number-of-days-between-two-dates) – Cyril Duchon-Doris Nov 02 '16 at 15:36

1 Answers1

4

Your form is most likely going to post to save data in rows of your database that represent an instance of a model. So you can use a model method (or, since some would argue that models should only contain persistence logic, a model decorator) to achieve this. For now, it's easiest to keep it in the model.

Say your model name is Event.

Then you can have start_date and end_date fields on it. These will likely be datetime fields.

Then, you can have a method in your model called, say, days_spread:

def days_spread
  end_date.to_date - start_date.to_date
end

Calling to_date on those datetimes will make the result of that subtraction a number of days. You may also need to call to_i on that return value to get an integer.

Then you can just call days_spread.times do { |x| }

It's hard to give you a more specific answer without your data model, but that should get you started.

nickcoxdotme
  • 6,567
  • 9
  • 46
  • 72