我有一个观察者,当记录(预订)的状态发生变化时,他会创建一些记录(票证)。运行应用程序时它工作正常。但不会在迁移期间或在 rails 控制台中运行。我能理解,它应该
这是在 application.rb
# Activate observers that should always be running.
config.active_record.observers = :booking_observer
这是观察者(booking_observer.rb)
编码:utf-8
class BookingObserver < ActiveRecord::Observer
require 'logger'
def create_ticket(booking, passenger, leg)
ticket = Ticket.factory(booking, passenger, leg)
begin
ticket.save!
rescue Exception => e
booking.logger.error "Can't save #{leg} ticket: #{e}"
end
end
def after_update(booking)
if booking.changed? && booking.changed_attributes()["status"]!=Booking::CONFIRMED && booking.status==Booking::CONFIRMED.to_sym
passengers = booking.passengers.all
passengers.each do |passenger|
booking.logger.error "Passenger: #{passenger}"
create_ticket(booking, passenger, Booking::DEPARTURE_LEG)
create_ticket(booking, passenger, Booking::RETURN_LEG) if booking.booking_type.to_sym != :ow
end
end
end
end
这是一个示例迁移
class CreateTicketsForValidBookings < ActiveRecord::Migration
def up
bookings = Booking.where("departure_date < ?", 1.minute.ago).where(status: "confirmed")
bookings.each do |booking|
booking.status="migrating"
booking.save
booking.status="confirmed"
booking.save
end
end
def down
bookings = Booking.where("departure_date < ?", 1.minute.ago).where(status: "migrating")
bookings.each do |booking|
booking.status="confirmed"
booking.save
end
end
end
在我发现的每一个帖子中,人们都试图禁用观察者。好吧,就我而言,它是倒退的