如何將mysql datetime字段轉換爲兩個表單字段(1)僅限日期,(2)僅限時間,並將兩個字段組合爲表單提交後的日期時間格式?Rails 4 - 將日期時間轉換爲單獨的日期和時間字段
這將允許使用下面的寶石,但日期存儲在一個日期時間字段:
gem 'bootstrap-datepicker-rails'
gem 'bootstrap-timepicker-rails'
提前感謝!
如何將mysql datetime字段轉換爲兩個表單字段(1)僅限日期,(2)僅限時間,並將兩個字段組合爲表單提交後的日期時間格式?Rails 4 - 將日期時間轉換爲單獨的日期和時間字段
這將允許使用下面的寶石,但日期存儲在一個日期時間字段:
gem 'bootstrap-datepicker-rails'
gem 'bootstrap-timepicker-rails'
提前感謝!
發現幫助解決從@Althaf
添加的虛擬屬性model.rb 用於before_save
回調轉換回日期時間。
before_save :convert_to_datetime
def sched_date_field
sched_date.strftime("%d/%m/%Y") if sched_date.present?
end
def sched_time_field
sched_time.strftime("%I:%M%p") if sched_time.present?
end
def sched_date_field=(date)
# Change back to datetime friendly format
@sched_date_field = Date.parse(date).strftime("%Y-%m-%d")
end
def sched_time_field=(time)
# Change back to datetime friendly format
@sched_time_field = Time.parse(time).strftime("%H:%M:%S")
end
def convert_to_datetime
self.sched_time = DateTime.parse("#{@sched_date_field} #{@sched_time_field}")
end
使用Rails 4,sched_date_field和sched_time_field在controller.rb添加到嚴格PARAMS需要
下面是字段_form.html.erb
<%= f.label :sched_date_field, "Scheduled Date" %>
<%= f.text_field :sched_date_field, :class => "datepicker" %>
<%= f.label :sched_time_field, "Scheduled Time" %>
<%= f.text_field :sched_time_field, :class => "timepicker" %>
如果您有專業訂閱the revised one,您可以使用虛擬屬性See this Railscast。
基本上在視圖中,您將以下
<%= f.label :date_field %>
<%= f.text :date_field %>
<%= f.label :time_field %>
<%= f.text :time_field %>
你的數據庫將仍然保持了場,我會打電話給full_date
現在,在你的模型,你必須定義上述2個領域如下。
def date_field # What this returns will be what is shown in the field
full_date.strftime("%m-%d'%y") if full_date.present?
end
def time_field
full_date.strftime("%I:%M%p") if full_date.present?
end
def time_field=(time)
full_date = DateTime.parse("#{date_field} #{time_field})
end
由於看起來您正在使用Rails 4,因此您必須在強參數中允許使用date_field和time_field。
你可以使用date_time_attribute gem:
class MyModel < ActiveRecord::Base
include DateTimeAttribute
date_time_attribute :scheduled_at
end
它將允許您分別設置schedule_at_date
和scheduled_at_time
。一旦設置了屬性,數值將被合併到schedule_at
中。
嚴格的參數,你的意思是「強烈的參數」?此外,這段代碼似乎在sched_time上引發了一個未定義的變量錯誤。 –
這是一個邊緣情況,但是如果你使用這種技術並且需要對'sched_time'字段進行任何驗證,它將會失敗。你可以嘗試把'before_save'改成'before_validation'。但是,如果你有級聯驗證,這可能會失敗。在這個簡短的評論中有點難以解釋,但相信我,它會失敗。 – Karl
@Karl你推薦什麼?我遇到了這個問題..我想改變我的數據模型,將日期,時間和時區存儲爲3個單獨的字段。 – Turgs