使用模块非常新。在验证它并将其保存到数据库之前,我无法让我的模块方法将用户输入的字符串(“1:48.55”)转换为浮点数。不知道我做错了什么......
配置/应用程序.rb
config.autoload_paths += %W(#{config.root}/lib/modules/)
lib/modules/sport_time.rb
module SportTime
extend ActiveSupport::Concern
attr_accessor :goal_time
included do
before_validation :sporty_save
end
def self.stringify_race(secs)
m = (secs/60).floor
s = (secs - (m*60))
sprintf("%02d:%.2f\n",m,s)
end
private
def sporty_save
self.goal_time = self.goal_time.floatify_race(goal_time) ---(line 12)---
end
def floatify_race(str)
dirty = str.split(":")
min = dirty[0]
sec = dirty[1]
seconds = (min.to_i * 60) + sec.to_f
seconds.round(4)
end
end
应用程序/模型/事件.rb
class Event < ActiveRecord::Base
include SportTime
validates_presence_of :event_type, :race_length, :course, :goal_time, :user_id
attr_accessible :event_type, :race_length, :course, :goal_time, :user_id
belongs_to :user
end
分贝/种子.rb
Event.create(
:event_type => 'Run',
:race_length => 800,
:course => 'outdoor',
:goal_time => '01:48.55',
:user_id => user_one.id
)
错误:
rake aborted!
undefined method `floatify_race' for "01:48.55":String
/Users/myname/work/projectname/lib/modules/sport_time.rb:12:in `sporty_save'
我究竟做错了什么?