0
所以在我看來,我使用日曆來選擇一天和下拉選擇時間。所以我使用的是before_validation
方法把它一起:試圖在before_validation中設置一個變量,但它不起作用
proposed_time.rb
before_validation :construct_starting_at
def construct_starting_at
d = Time.parse(date)
puts "************** construct_starting_at BEGIN *****************"
puts "DATE: #{d}"
puts "Time: #{time}"
puts "Timezone: #{timezone}"
puts "construct_starting_at :: #{d.year}-#{d.month}-#{d.day} #{time.hour}:#{time.min}:00 #{timezone}"
if date.present? && time.present? && timezone.present?
starting_at = Time.zone.parse("#{d.year}-#{d.month}-#{d.day} #{time.hour}:#{time.min}:00 #{timezone}")
end
puts "starting_at: #{starting_at}"
puts "************** construct_starting_at END *****************"
end
,當我創建一個對象,它工作得很好,但不是當我更新它。
日誌
************** construct_starting_at BEGIN *****************
DATE: Fri Jun 03 00:00:00 -0500 2011
Time: Thu May 19 23:00:00 UTC 2011
Timezone: (GMT-05:00) Eastern Time (US & Canada)
construct_starting_at :: 2011-6-3 23:0:00 (GMT-05:00) Eastern Time (US & Canada)
starting_at: 2011-06-04 00:00:00 -0400
************** construct_starting_at END *****************
但是當我用它的更新也完全失去它並回復到它是什麼。這讓我覺得它實際上並沒有被保存。因此,爲了幫助這個下一個解釋方面,我有一個ProposedTime
對象,它是Consultation
一個孩子(每次磋商已提出3次)也有accepts_nested_attributes_for :proposed_times
:
consultation.rb
def proposed_times_attributes=(attributes)
puts "$$$$$$$$$$$$$$ proposed_times_attributes $$$$$$$$$$$$$$$$"
attributes.each do |key,value|
value[:timezone] = timezone
if value[:id]
puts "Updating #{value[:id]}"
p = ProposedTime.find(value[:id])
value.delete(:id)
unless p.update_attributes(value)
puts "@@@@@@@@@@@@@@@@@ ERROR @@@@@@@@@@@@@@@"
error.add(:proposed_times, "something is wrong")
end
puts "-- starting_at: #{p.starting_at}"
else
puts "Creating a new proposed time"
proposed_times << ProposedTime.new(value)
end
end
puts "$$$$$$$$$$$$$$ proposed_times_attributes $$$$$$$$$$$$$$$$"
end
日誌
...
Updating 18
************** construct_starting_at BEGIN *****************
DATE: Fri Jun 03 00:00:00 -0500 2011
Time: Thu May 19 23:00:00 UTC 2011
Timezone: (GMT-05:00) Eastern Time (US & Canada)
construct_starting_at :: 2011-6-3 23:0:00 (GMT-05:00) Eastern Time (US & Canada)
starting_at: 2011-06-04 00:00:00 -0400
************** construct_starting_at END *****************
-- starting_at: 2011-06-01 06:00:00 -0400
我想這可能已經在update_attri拋出一個錯誤butes,但它似乎並不是這樣。有任何想法嗎?
任何知道何時使用'self.'的建議以及何時不需要?或者是最好的做法是始終使用它?感謝你的回答! – RyanJM 2011-05-20 13:30:57
設置實例/對象變量時使用它。如果您正在調用方法或獲取實例/對象變量的值,那麼不需要self。 – pat 2011-05-20 13:43:37
感謝您的快速響應。很有幫助。 – RyanJM 2011-05-20 13:45:32