我正在构建一个表单,用户可以输入像"08:00“或"3:10”这样的字符串形式的持续时间。我的想法是在before_validation
回调中将其转换为正确的秒数。
但不知何故,Rails在回调之前做了一些事情,因为当用户输入"08:00"
时,值总是为"0"
;当用户输入"3"
时,值总是为"3:10"
。
在我的身体里没有发生任何傲慢的事情;
<%= f.text_field :duration, required: true, class: 'input' %>
在我的控制器中;
def create
@entry = Entry.new entry_params
end
private
def entry_params
params.require(:entry).permit(:date, :duration, :project_id)
end
或者在我的模型中;
class Entry < ApplicationRecord
belongs_to :project
validates :duration, presence: true
before_validation :normalize_duration
def duration_formatted(format = '%H:%M')
Time.at(duration).utc.strftime format
end
private
def normalize_duration
# Always receiving the first character here :(
p self.inspect
end
end
发布于 2019-01-04 02:27:07
您需要覆盖活动记录生成的def duration=(值)方法。您必须这样做,而不是使用之前的验证:
def duration=(value)
seconds = Time.parse(value).utc.to_i - Time.parse("00:00").utc.to_i
self[:duration] = seconds
end
https://stackoverflow.com/questions/54026287
复制相似问题