开发者

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?


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


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"]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜