0

我有一个我想简化的表格。我正在记录一个开始日期和一个结束日期,但想只向用户显示一个开始日期,然后是一个带有天数的下拉列表。

但是我的模型存在问题并正确存储它。

第一部分有效。

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

我遇到的问题与结束日期基于 startdate + no_days 的事实有关,no_days 本身就是一个虚拟属性。我尝试将第二部分作为 after_validation 回调,但它似乎不起作用。

  def set_dates
    if self.startdate
      self.enddate = self.startdate + days
    end  
  end
4

1 回答 1

1

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
于 2010-10-13T15:31:34.380 回答