How can I make Rails ActiveRecord automatically truncate values set to attributes with maximum length?

Viewed 3561

Assuming that I have a class such as the following:

class Book < ActiveRecord::Base

  validates :title, :length => {:maximum => 10}

end

Is there a way (gem to install?) that I can have ActiveRecord automatically truncate values according to maximum length?

For instance, when I write:

b = Book.new
b.title = "123456789012345" # this is longer than maximum length of title 10
b.save

should save and return true?

If there is not such a way, how would you suggest that I proceed facing such a problem more generally?

4 Answers

I like the idea of using the before_validation callback. Here's my stab that automatically truncates all strings to within the database's limit

  before_validation :truncate_strings

  def truncate_strings
    self.class.columns.each do |column|
      next if column.type != :string

      if self[column.name].length > column.limit
        self[column.name] = self[column.name][0...column.limit]
      end
    end
  end
Related