开发者

How should my Rails before_validation callbacks handle bad data?

I have several before_validation callbacks that operate on the attributes being set on my model. I run into trouble when I have a situation like this:

class Foo < ActiveRecord::Base

  before_validation :capitalize_title
  validates :title, :presence => true

  def capitalize_title
    title.upcase
  end

end

I write a test to ensure that 'nil' title is not allowed, but the test gets an error because the nil.upcase is not defined. I'd like to handle this error, but I already have error handling that runs after before_validation callbacks.

I don't want to put checks 开发者_如何学运维around all of my before_validation callbacks to make sure the data exists, if I can avoid it.

Is there a clean or accepted way to deal with this type of situation?


Just check if you have a title. And don't forget to save the modified title.

def capitalize_title
  title = title.upcase if title
end

If you need to patch things up with a before_validation hook then you're stuck with taking care of invalid data in two places. If your validation was complicated you could factor it into two pieces: one piece that has to be true before the before_validation can run and one piece that has to be true after the before_validation has run:

before_validation :mangle_data
validate :data_is_okay

#...

def mangle_data
    return if(!data_is_mangleable)
    #... mangle away
end

def date_is_okay
    if(!data_is_mangleable)
        # complain
    end
    if(!data_is_properly_mangled)
        # complain some more
    end
end

def data_is_mangleable
   return false if(thing.nil?)
   # etc.
end

def data_is_properly_mangled
   # check that stuff that the before_validation hook doesn't
   # have to care about.
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜