这是架构和我的访问模式(访问状态可以是:确认,当前,已过期和待批准)
schema.rb
create_table "visits", force: true do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.date "start"
t.date "end"
t.integer "idVisit"
t.integer "employee_id"
t.integer "visitor_id"
t.string "status", default: "Confirmed"
end
Visit.rb
class Visit < ActiveRecord::Base
belongs_to :employee
belongs_to :visitor
default_scope -> { order(:created_at) }
validates :start, presence: true, uniqueness: {scope: [:end, :visitor_id]}
validates :end, presence: true
validates :visitor_id, presence: true
validates :employee_id, presence: true
validate :valid_date_range_required
def valid_date_range_required
if (start && end) && (end < start)
errors.add(:end, "must be after start")
end
end
end
现在我的问题是我需要比较每次访问,每次我在employee_controller.rb中显示操作,开始和结束日期到Date.today(除了被批准状态);根据它,我将改变数据库中的访问状态。
这是我做的,但可能会有一些错误,因为现在至少会发生错误,所以我希望你能帮我修复它。
在 Visit.rb 中我创建了这个:
def check_visit_status(visit)
if visit.status != 'To be confirmed'
if visit.start <= Date.today && visit.end >= Date.today
visit.status = 'Current'
end
if visit.end < Date.today
visit.status = 'Expired'
end
end
end
现在在 employees_controller.rb 我有(我不会发布所有内容):
class EmployeesController < ApplicationController
after_action :update_status, only: :show
def show
if logged_in?
@employee = Employee.find(params[:id])
@indirizzimac = current_employee.indirizzimacs.new
@visitor = current_employee.visitors.new
@visit = current_employee.visits.new
@visits = current_employee.visits.all
if params[:act]=='myData'
render 'myData'
elsif params[:act]=='myNetwork'
render 'myNetwork'
elsif params[:act]=='temporaryUsers'
render 'temporaryUsers'
elsif params[:act]=='guestsVisits'
render 'guestsVisits'
elsif params[:act]=='myAccount'
render 'myAccount'
else
render 'show'
end
else
render 'static_pages/errorPage'
end
end
def update_status
if @visits.any?
@visits.each do |visit|
check_visit_status(visit)
end
end
end
end
提前多多谢谢你
答案 0 :(得分:1)
我真的要感谢eeeeeean的巨大帮助。
我想出了我的问题,所以我想在这里发布我的解决方案,以帮助某人寻找我要求的同样的东西。
<强> employees_controller.rb 强>
class EmployeesController < ApplicationController
after_action :update_status, only: :show
def show
[...]
end
def update_status
if @visits.any?
@visits.each do |visit|
visit.check_visit_status
end
end
end
end
<强> Visit.rb 强>
def check_visit_status
if self.status != 'To be confirmed'
if self.start <= Date.today && self.end >= Date.today
self.update_attribute :status, 'Current'
end
if self.end < Date.today
self.update_attribute :status, 'Expired'
end
end
end
答案 1 :(得分:0)
您需要在访问实例上调用check_visit_status
,但现在它在self
上被调用,在此范围内调用员工控制器。试试这个:
<强> visit.rb 强>
def check_visit_status
if self.status != 'To be confirmed'
if self.start <= Date.today && end >= Date.today
self.status = 'Current'
end
if self.end < Date.today
self.status = 'Expired'
end
end
end
然后这样称呼:
<强> employees_controller.rb 强>
@visits.each do |visit|
visit.check_visit_status
end
这应该让你摆脱那个特定的错误。