首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么我的属性字符串在Rails中转换为数字

为什么我的属性字符串在Rails中转换为数字
EN

Stack Overflow用户
提问于 2019-01-04 00:33:42
回答 1查看 49关注 0票数 0

我正在构建一个表单,用户可以输入像"08:00“或"3:10”这样的字符串形式的持续时间。我的想法是在before_validation回调中将其转换为正确的秒数。

但不知何故,Rails在回调之前做了一些事情,因为当用户输入"08:00"时,值总是为"0";当用户输入"3"时,值总是为"3:10"

在我的身体里没有发生任何傲慢的事情;

代码语言:javascript
复制
<%= f.text_field :duration, required: true, class: 'input' %>

在我的控制器中;

代码语言:javascript
复制
def create
  @entry = Entry.new entry_params
end

private 

def entry_params
  params.require(:entry).permit(:date, :duration, :project_id)
end

或者在我的模型中;

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-04 02:27:07

您需要覆盖活动记录生成的def duration=(值)方法。您必须这样做,而不是使用之前的验证:

代码语言:javascript
复制
    def duration=(value)
      seconds = Time.parse(value).utc.to_i - Time.parse("00:00").utc.to_i

      self[:duration] = seconds
    end
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54026287

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档