How can I get Rails ActiveRecord to automatically trim the values ​​set for attributes with the maximum length?

Assuming I have a class such as:

class Book < ActiveRecord::Base validates :title, :length => {:maximum => 10} end 

Is there a way (gem to install?) That ActiveRecord can automatically trim values ​​to fit the maximum length?

For example, when I write:

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

should keep and return true?

If there is no such way, how would you suggest that I am more likely to encounter such a problem?

+8
max ruby-on-rails activerecord attributes
source share
3 answers

I came up with a new validator that does truncation. Here is how I did it:

I created the “validators” folder inside the “app” folder, and then created the file “length_truncate_validator.rb” with the following contents:

 class LengthTruncateValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) ml = options[:maximum] record.send("#{attribute}=", value.mb_chars.slice(0,ml)) if value.mb_chars.length > ml unless value.nil? or ml.nil? end class << self def maximum(record_class, attribute) ltv = record_class.validators_on(attribute).detect { |v| v.is_a?(LengthTruncateValidator) } ltv.options[:maximum] unless ltv.nil? end end end 

And inside my model class, I have something like:

 class Book < ActiveRecord::Base validates :title, :length_truncate => {:maximum => 10} end 

which is very convenient and works as I need.

But still, if you think that this can be improved or done differently, please.

+2
source share

Well, if you want the value to be truncated, if it is too long, you really don't need a check because it will always pass. I would handle it like this:

 class Book < ActiveRecord::Base before_save :truncate_values def truncate_values self.title = self.title[0..9] if self.title.length > 10 end end 
+5
source share

This may not be an option in 2011, but now there is a before_validation that will work.

 class Book < ApplicationRecord before_validation do if self.params && self.params.length > 1000 self.params = self.title[0...10] end end validate :title, length: { maximum: 10 }, allow_nil: true end 
0
source share

All Articles