需要捕获几小时的整数并将其作为日期时间保存到我的数据库中

时间:2012-03-05 10:42:19

标签: ruby-on-rails ruby forms

编辑:我将时间数学移动到模型中作为回调。我收到了这个错误:

NoMethodError in OutstandingsController#create
undefined method `hours' for nil:NilClass

为了能够做数学时间,我需要包含一些宝石吗?我以为它包含在ActiveSupport中..?

class Outstanding < ActiveRecord::Base
  belongs_to :user

  before_validation(:on => :create) do
    self.panic_deadline = Time.now
    self.panic_deadline = self.panic_deadline + self.deadline_hours.hours
    self.panic_deadline = self.panic_deadline + self.deadline_minutes.minutes

    self.active = true
  end
end

class OutstandingsController < ApplicationController

def create
    @outstanding = Outstanding.new(params[:outstanding])
    @user = current_user
    @outstanding.user_id=@user.id

    respond_to do |format|
      if @outstanding.save ...

<%= form_for(@outstanding) do |f| %>
  <div class="field">
    <%= select_tag :deadline_hours, options_for_select(Array(0..99), 0)  %><%= f.label :deadline_hours %>
    <%= select_tag :deadline_mins, options_for_select(Array(1..59), 30) %><%= f.label :deadline_mins %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

3 个答案:

答案 0 :(得分:0)

您可以按照Ruby docs for Time

中所示对Time对象执行计算
time = Time.now
time += (60 * 60) # Time is now 1 hour from now

我认为我的数学是正确的:P

答案 1 :(得分:0)

也许像

panic_deadline = Time.now
panic_deadline = panic_deadline + @outstanding.deadline_hours.hours
panic_deadline = panic_deadline + @outstanding.deadline_minutes.minutes

确保deadline_hours / deadline_minutes的虚拟属性或模型架构中的虚拟属性。

class Outstanding < ACtiveRecord::Base
  belongs_to :user

  before_validation(:on => :create) do
    self.panic_deadline = Time.now
    self.panic_deadline = self.panic_deadline + self.deadline_hours.hours
    self.panic_deadline = self.panic_deadline + self.deadline_minutes.minutes
    self.active = true
  end

  attr_accessor           :deadline_hours, :deadline_minutes

end

答案 2 :(得分:0)

这可能是你想要的:

@outstanding.deadline_hours.hours.since(@outstanding.deadline_mins.minutes.from_now)

你应该在回调或观察者中计算。