vmarquet
vmarquet

Reputation: 2532

rails string limit does not prevent too long strings from being inserted in db

I wrote a migration for a Rails 4 project to add a character limit to a string column. I used the following code:

change_column :articles, :name, :string, :limit => 40

The migration with rake db:migrate went fine, resulting in the following line in db/schema.rb:

t.string   "name",  limit: 40,  null: false

But when I enter a string with more than 40 characters in the form (generated by a scaffold), there isn't any error message and the too long string is inserted in the database.

What am I doing wrong ?

Upvotes: 2

Views: 746

Answers (1)

Jason E. Wall
Jason E. Wall

Reputation: 96

Depending on the RDBMS you're using, the field limit won't be validated at the database level. To ensure you're getting great error messages when your constraints are being violated, use ActiveRecord validations.

Try: validates_length_of :name, maximum: 40

In your model class.

Upvotes: 1

Related Questions