簡體   English   中英

Rails將date_select轉換為int值

[英]Rails Convert date_select to an int value

在Rails 3.x中,我有一個帶有int字段“ my_int_date”的模型類。 我希望將int字段填充為date_select表單元素的表單。

問題是,當表單讀取date_select值時,它會以多參數值的形式將其發送回,從而導致錯誤

1 error(s) on assignment of multiparameter attributes

無論如何,我可以將其作為日期存儲在模型中,但是在將其轉儲到數據庫時將其轉換為int嗎?

Ruby可以使用to_i將Time對象轉換為秒

Time.now.to_i # Returns epoc time (s)

如果是字符串,則可以使用to_time方法

'2012-06-01'.to_time.to_i # string to Time object then to epoc time (s)

這是我解決的方法

在我的ActiveRecord模型中,我添加了字段

attr_accessible :my_int_date_time

columns_hash["my_int_date_time"] = ActiveRecord::ConnectionAdapters::Column.new("my_int_date_time", nil, "DateTime")

def my_int_date_time
  return TimeHelper.datetime_from_integer(self.my_int_date)
end

def my_int_date_time= val
    self.my_int_date = TimeHelper.datetime_to_integer(val)
end

然后在我的表單中,將datetime字段鏈接到my_int_date_time字段,而不是將其鏈接到my_int_date

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM