2013-03-04 54 views
0

我希望用户能够选择或输入时间(例如:“您花费多长时间刷牙早上?“)和”创建“或”更新“操作,我想将时间转换为在发布/放入数据库之前的秒数。在POST/PUT到数据库之前将时间(MM:SS)转换为浮点数(秒)

我有一个模块中的方法,现在(努力学习如何使用模块),但我不知道这是否是适合这种情况... ...

float到时间的视图(作品)

<%= MyModule.float_to_time(task.task_length) %> 

模块

module MyModule 

    def self.float_to_time(secs)  # task.task_length (view) 
    ... 
    ... 
    end 

    def self.time_to_float(tim)  # :task_length (controller) 
    m = tim.strftime("%M").to_f 
    s = tim.strftime("%S.%2N").to_f 
    t = ((m*60) + s) 
    return t.round(2) 
    end 

end 

控制器

def create 
    # "time_to_float" (Convert task_time to seconds float) 
    # Create new task after conversion 
    @task = Task.new(params[:task]) 

    respond_to do |format| 
    if @task.save 
     format.html { redirect_to @task, notice: 'Task was successfully created.' } 
     format.json { render json: @event, status: :created, location: @task } 
    else 
     format.html { render action: "new" } 
     format.json { render json: @task.errors, status: :unprocessable_entity } 
    end 
    end 
end 

我该怎么做后转换前(或认沽)的分贝?

另外,我应该将这些方法移至application_controller,还是我的模块正常?

- 感谢您的任何帮助。

+1

不要忘了'//'不会在Ruby中开始评论。 '#'确实。您可能想编辑您的帖子以反映这一点。 – 2013-03-04 13:41:08

+0

哎呦,脑屁。感谢Charles。 – econduck 2013-03-04 13:53:55

回答

1

对我来说,这看起来像是模型的工作,而不是控制器。该模型应该关心数据如何存储以及适当转换数据类型。

既然你想学习如何使用的模块,你可以保持一个模块实例方法在这些方法中,并将它们混合到你的模型类:

module TimeConversions 
    def time_to_float(time) 
    # ... 
    end 

    def float_to_time(seconds) 
    # ... 
    end 
end 

class Task 
    extend TimeConversions 
    before_save :convert_length 

    # ... 

private 

    def convert_length 
    self.length = self.class.time_to_float(length) if length.to_s.include?(':') 
    end 
end 

,那么你仍然可以使用float_to_time在观点:

<%= Task.float_to_time(task.length) %> 

你可能会做一些更复杂的在你的before_save过滤器,但也许这会给你一些想法。

+0

不能要求更多。感谢Brandan。 – econduck 2013-03-04 14:16:11

1

我认为你正在寻找一个ActiveRecord Callback

在此,如果你也有类似:

class Task < ActiveRecord::Base 
    before_save :convert_task_length_to_float 

    def convert_task_length_to_float 
    # do the conversion. set `self.task_float =` to update the value that will be saved 
    end 
end 

before_save回调Task之前将调用保存到数据库中。

1

此外,您可以覆盖task_length访问器的setter和getter。像这样(在任务模式中):

class Task < ActiveRecord::Base 

    def task_length=(tim) 
    m = tim.strftime("%M").to_f 
    s = tim.strftime("%S.%2N").to_f 
    t = ((m*60) + s) 
    write_attribute(:task_length, t.round(2)) 
    end 

    def task_length_to_time 
    tl = read_attribute(:task_length) 
    # ... float-to-time stuff 
    end 
end 

然后在视图中使用它<%= task.task_length_to_time %>。如果您需要浮动,请使用task.task_length