I have a virtual attribute start_date
and a database column start
(datetime).
How can i override the date (but not the time) of start
with the date from start_date
?
I tried this in the setter method and the logger says that self.start/start is set, but in the database and also the update log start
has still the old date.
# model: db table with columns: id(int), start(datetime)
class DateTimeTest < ActiveRecord::Base
attr_accessible :start_date, :start
def start_date=(value)
logger.debug '>>>>' + start.inspect
logger.debug '>>>>' + self.start.inspect
start = DateTime.new(value.to_date.year, value.to_date.month, value.to_date.mday, 15,15,15)
self.start = DateTime.new(value.to_date.year, value.to_date.month, value.to_date.mday, 15,15,15)
logger.debug '>>>>' + start.inspect
logger.debug '>>>>' + self.start.inspect
end
end
# view
<%= simple_form_for(@datetimetest) do |f| %>
<%= f.input :start_date, :as => :string %>
<%= f.input :start %>
<%= f.button :submit %>
<% end %>
# controller is a base scaffolding controller
In the logs i can see that start
is populated:
Parameters: {..., "datetimetest"=>{"start_date"=>"03.05.2012", "start(1i)"=>"2012", "start(2i)"=>"5", "start(3i)"=>"1", "start(4i)"=>"13", "start(5i)"=>"05"}
The DateTime decomposes into year, month, date of month, hour, minute, and second, but does not conveniently break into date and time.
def start_date(value)
start = DateTime.new(value.year, value.month, value.mday,
start.hour, start.minute, start.second)
logger.debug self.start.inspect
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.