我正在尝试创建一个范围,它是活动的,用于查询5个小时的类Shift的条目。然后我尝试将范围应用到Shift的实例,这样我就可以让shift控制器重定向以显示活动的移位。这是shift.rb:
class Shift < ActiveRecord::Base
scope :active, -> { where(created_at: (Time.now.ago(5.hours)..Time.now)) }
validates :created_at, uniqueness: true
validates_time :created_at, :between => ['9:30pm', '2:30am']
validate :active_shift_limit
private
def active_shift_limit
if Shift.active.count >= 1
errors.add(:base, "Shift already exists for tonight")
end
end
end
首先,我遇到了范围问题。我在8小时前创建了一个班次,并在控制台中查询它。
Shift.active.exists?
Shift Exists (0.2ms) SELECT 1 AS one FROM "shifts" WHERE ("shifts"."created_at" BETWEEN '2015-09-14 22:48:35.929658' AND '2015-09-15 03:48:35.929768') LIMIT 1
=> true
所以我看看这个条目。
Shift.active
Shift Load (0.2ms) SELECT "shifts".* FROM "shifts" WHERE ("shifts"."created_at" BETWEEN '2015-09-14 23:03:38.195154' AND '2015-09-15 04:03:38.195191')
=> #<ActiveRecord::Relation [#<Shift id: 32, shift_id: nil, vehicle_id: nil, user_id: nil, created_at: "2015-09-15 00:11:32", updated_at: "2015-09-15 00:11:32">]>
范围是在明天注册一个范围,我不知道为什么,所以我尝试进入我已经将范围放入控制台的范围,看看问题是否存在:
Time.now.ago(5.hours)..Time.now
=> 2015-09-14 16:08:35 -0700..2015-09-14 21:08:35 -0700
好的。在这一点上,我很难过。我哪里错了? 至于问题的第二部分,在Shift的实例上调用范围,我也很难过。经过一些修补,我意识到范围是一种类方法。所以我想在方法上调用它并将其置于实例变量中将起作用。没有雪茄。我收到这个错误:
ActiveRecord::RecordNotFound in ShiftsController#create
"Couldn't find Shift without an ID"
这是我的shifting_controller.rb:
class ShiftsController < ApplicationController
skip_before_filter :verify_authenticity_token, :only => :create
def show
@shift = Shift.find(params[:id])
end
def create
@active_shift = Shift.active
if Shift.active.exists?
redirect_to shift_path(@active_shift)
else
@shift = Shift.new
@shift.save
redirect_to shift_path(@shift)
end
end
end
我在shift.rb中使用此gem用于validates_time:
gem 'jc-validates_timeliness', '~> 3.1.1'
。我在确定范围时大量引用了这一点:How do I validate one post per day?