2

I have an object that is apparently randomly getting set to an id of 1 and the source of where this is happening is unknown in the codebase. Could be on an update attributes for a user for which school is associated.

How can I raise an error or otherwise log when this happens so I can track it down and resolve it?

Below is a first attempt but doesn't seem to take into account update_attributes

belongs_to :foo_school, :foreign_key => 'school_id'

def foo_school=(foo_school)
  begin
    raise "Found" if foo_school == FooSchool.find(1)
  rescue Exception => e
    # Track it down through the stack trace
    Rails.logger.error e
  ensure
    write_attribute(:foo_school, foo_school)
  end
end
2
  • Stack traces? Full code? What does foo_school contains? It's really hard to understand what's happening here with only this much information. Commented Sep 4, 2011 at 20:37
  • That is in the scope of a model that belongs_to a FooSchool. It doesn't matter what FooSchool contains other than an id. All I want to do is raise an error when an associated model, FooSchool, is updated with an id of 1. Commented Sep 4, 2011 at 20:58

1 Answer 1

2

An observer can do this for you. What you do with this observer is up to you.

$ rails g observer Oddity

Add this in config/application.rb (search for "observer" in that file, there's an example by default). config.active_record.observers = :oddity_observer

class OddityObserver < ActiveRecord::Observer
  observe :foo

  def after_update(record)
    raise "Boom" if record.id == 1
  end 
end
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.