Ruby on rails - shrink length of an entry on validation

I want to limit the size of the data and if it exceeds i want it to be to shrinked to the limit. is there any easy way to do this??

my validation code:

validates :title, :presence => true, :length => { :maximum => 80 }

for example the data is:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore

i want it to be shrinked to:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod temp...


Please refer to ActiveRecord callbacks, you should do this in before_validation. You can truncate the string with String#truncate provided by ActiveSupport.


before_validation do
  self.title = title.truncate(80, :omission => '...')

I would just put this in a before_create function since you are not really validating anything - you just want the data changed under certain conditions. Also, you might want to consider keeping the long title and making a function like short_title that returns a shrunk version - this gives you the same functionality and you might end up needing the longer title.

before_create :shrink_title


def shrink_title
  self.title = title[0...77] + '...' if title.length > 80


def short_title
  (title.length > 80) ? title[0...77] + '...' : title

Need Your Help

Disable font animation in UIButton

ios objective-c uibutton uiviewanimation ios-animations

I am animating a view that is sliding down. In the view there is a simple UIButton. The view and the button have fixed widths and heights (I checked with adding a color as background). Although whe...

How to handle Drag and Drop Properly using PYQT QAbstractItemModel

pyqt qtreeview qtreewidget qabstractitemmodel qtreewidgetitem

Here is a code I ended up after two days of TreeView/Model madness. The subject appeared to be much more broad than I thought. I barely can spend so much time creating a singe widget. Anyway. The

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.