views:

25

answers:

1

I have a form which i'd like to simplify. I'm recording a startdate and an enddate, but would like to show the user only a startdate and then a drop down with number of days.

But I'm having problems with my model and storing it correctly.

The first part works.

  def date=(thedate)
     #puts the startdate in the correct format...
     self.startdate = Date.strptime(thedate, '%m/%d/%Y')
  end

The problem I have has to do with the fact that the end date is based on the startdate + the no_days which is itself a virtual attribute. I tried doing the second part as a after_validation callback but it doesn't seem to work.

  def set_dates
    if self.startdate
      self.enddate = self.startdate + days
    end  
  end
+1  A: 

First of all, why do you need to convert a date attribute in your startdate? Why don't you use something like f.date_select :startdate in you form?

Then, in your model you need something like attr_accessor :number_of_days with wich you can get the number_of_days as an integer in your form with f.select :number_of_days, (1..10).to_a (set the array as you like).

You can set your callback the following way:

after_validation :set_enddate

def set_enddate
  if self.startdate
    self.enddate = self.startdate + self.number_of_days.days
  end
end
Yannis
beautiful thanks. I'm using the first date virtual attribute because I don't like the date_select helper and am using a textfield with jq-ui datepicker.
holden