Zabba
Zabba

Reputation: 65497

How to intercept assignment to attributes?

I have a bug where in a associated model, the parent model's foreign key is coming as NULL in the associated model's table.

To track down why this is happening, I would like to write to the log file each time an attribute is assigned-to (i.e. every call made to attr= methods).

How can I do this? Does Rails already allow this to be done via some way that I do not know of?

Upvotes: 2

Views: 630

Answers (2)

Ashish
Ashish

Reputation: 5791

I think you can use callback methods (before_save)to check the status of your object. And following might help you...

article = Article.find(:first)
article.changed?  #=> false

# Track changes to individual attributes with
# attr_name_changed? accessor
article.title  #=> "Title"
article.title = "New Title"
article.title_changed? #=> true

# Access previous value with attr_name_was accessor
article.title_was  #=> "Title"

# See both previous and current value with attr_name_change accessor
article.title_change  #=> ["Title", "New Title"]

Upvotes: 1

Pan Thomakos
Pan Thomakos

Reputation: 34350

You can do it by simply overwriting the attr= method. For example:

class User
  def username= username
    Rails.logger.info "Setting username with #{username}"
    write_attribute :username, username
  end
end

You can also accomplish this by chaining methods. For example:

class User
  alias :username_old= :username=
  def username= username
    Rails.logger.info "Setting username with #{username}"
    self.username_old = username
  end
end

Upvotes: 3

Related Questions