我在start_time:timestamps
表格中有finish_time:timestamps
和events
个字段。所以我想在这里只存储几小时和几分钟。
_form.html.erb
<%= f.time_select :start_time_string %>
我在模型中添加了虚拟属性。
event.rb
# Generates methods: start_time_string, finish_time_string
#
[:start_time, :finish_time].each do |field_name|
define_method("#{field_name}_string") do
self.send(field_name).strftime('%H:%M') if self.send(field_name)
end
end
[:start_time, :finish_time].each do |field_name|
define_method("#{field_name}_string=") do |time|
self.send(field_name) = time.strftime('%H:%M')
end
end
但我收到了错误:
syntax error, unexpected '=', expecting keyword_end self.send(field_name) = time.strftime('%H:%M') ^
为什么会这样?如果有可能,请你为我提出更好的解决方案吗?
答案 0 :(得分:1)
替换
[:start_time, :finish_time].each do |field_name|
define_method("#{field_name}_string=") do |time|
self.send(field_name) = time.strftime('%H:%M')
end
end
与
[:start_time, :finish_time].each do |field_name|
define_method("#{field_name}_string=") do |time|
self.send("#{field_name}_string=",time.strftime('%H:%M'))
end
end
修改强>
这将创建两个方法start_time_string=
和finish_time_string=
。
您可以将这些称为
start_time_string = Time.now
finish_time_string = Time.now
答案 1 :(得分:1)