Set maximum length in Text field in RoR

Client Side:

      <%= text_field_tag :"description", '', maxlength: 5   %>
   or      
     <input type="text" name="description" id="description" value="" maxlength="5">

Server Side: That is inside the model.rb file

validates_length_of :column_name, :maximum => 5

Here is how you can do it:

<%= text_field_tag 'create_text', nil, :maxlength => 15, :size => 40 %>

Source: http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-text_field_tag


In the text_field_tag call:

:size relates to the physical length of the text box. It will be big enough to allow that many characters to be visible in the box. But the user can still enter more.

:maxlength is the maximum number of characters the user can enter, regardless of the physical size of the text box. The text box can be bigger or smaller, but if you set :maxlength => 5, they will only be able to enter 5 characters.

If this is a hard limit you want for the data in the database, too, you should set a validation. This prevents you from, for example, setting it to more characters in your Rails code.

validates_length_of :column_name, :maximum => 5

Finally, for a belts and suspenders approach and to prevent even code that goes against the database from setting a bad value, you can enforce it at the database level. In some cases, other code than your Rails app might update the database. This prevents bad data even in this case.

Adding a column in a migration you do it like this:

add_column :table_name, :column_name, :string, :limit => 30