我有一个观察员在记录(预订)状态发生变化时创建一些记录(票证)。它在运行应用程序时工作正常。但是在迁移期间或在rails控制台中不会运行。我可以理解,它应该
这是在application.rb
# Activate observers that should always be running.
config.active_record.observers = :booking_observer
heres是观察者(booking_observer.rb)
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
在我发现的每一篇文章中,人们都试图禁用观察者。好吧,就我而言,它是向后的
答案 0 :(得分:1)
事实证明,你必须在每个环境的基础上启用观察者。这三个文件
config/enviroments/development.rb
config/enviroments/test.rb
config/enviroments/production.rb
必须激活应始终使用。
运行的观察者config.active_record.observers = :booking_observer