Friday, April 22, 2011

Inside rails.

You must be very careful when create "before_*" callbacks in Rails.

I found one interesting feature (of course it is not bug :D ) ActiveRecord raise with error RecordNotSaved if you have "before_*" callback that return "false". For example:

class User < ActiveRecord::Base
  before_save :set_short_link

  private
  def set_short_link
    short_link = name.to_url if name.changed?
  end
end

You can`t save instance of this class if you don`t change "name" because method "set_short_link" return false (see /activerecord/lib/active_record/base.rb, line 2568)

Right version will be:

class User < ActiveRecord::Base
  before_save :set_short_link

  private
  def set_short_link
    short_link = name.to_url if name.changed?
    true
  end
end

1 comment:

  1. Thanks for reply.
    But... this is a fiction example. I never wrote this code. I just try to tell about interesting features that i found in before_* callbacks.

    ReplyDelete