2013-06-28 51 views
0

的Rails 3.2.8訪問date_select之前保存

在這個模型中,我無法訪問雲集的形式start_date

# form 
<div class="field"> 
    <%= f.label :start_date %><br /> 
    <%= f.date_select :start_date %> 
</div> 
<div class="field"> 
    <%= f.label :total_months %><br /> 
    <%= f.number_field :total_months %> 
</div> 


# model 
attr_accessible :expire_date, :start_date, :total_months 

def total_months=(total) 
    write_attribute :expire_date, start_date + 3.months 
end 

我得到一個nil錯誤,因爲start_date返回nil。我怎樣才能獲得日期格式的start_date?

+0

你的方法只覆蓋了'total_months'屬性設置方法,而你不知道這是否會之前或'start_date'屬性設置後設置(它可能不會按照視圖中給出的順序發生)。嘗試在'before_save'回調中執行'write_attribute:expire_date,start_date + 3.months'。另外,除了'total_months'屬性設置器外,它看起來像是在重寫'total_months'屬性設置器,所以'total_months'不會被設置。 – lurker

+0

我拿出了與問題無關的部分代碼(例如在setter函數中設置total_months值)。你讓我朝着正確的方向!有一個before_save回調正是我需要採取的路線。謝謝! –

+0

很酷。謝謝。 – lurker

回答

1

您的方法只覆蓋total_months屬性的設置方法,並且您不知道將在設置start_date屬性之前還是之後設置此屬性(它可能不會按照視圖中給出的順序發生)。嘗試在before_save回調中執行write_attribute :expire_date, start_date + 3.months

因此,像:

before_save :do_before_save 

def do_before_save 
    self.expire_date = start_date + 3.months if start_date 
end