Jay
Jay

Reputation: 65

Rails 4: Modifying an existing model column

When I have a column named "fullname" in the existing model, I want to set a limit of 50 characters to store in that column. What is the best method to achieve this? Use rails migrate? or code something in app/models to do syntax checking?

Upvotes: 0

Views: 323

Answers (1)

Charlie Martin
Charlie Martin

Reputation: 8406

You should really do both. You want your database to enforce your data restrictions as this prevents any bugs in your application code from allowing invalid data. Create a rails migration to alter the data type of your column. For example...

change_table :table_name do |t|
  t.change :column_name, :string, :limit => 50
end

You should also ensure the data is less than 50 characters in your application code, otherwise you will get an error if you try to insert a value greater than 50 characters. The rails way to do this would be an Active Record Validation in your model. See this link for info on Active Record validations

Upvotes: 1

Related Questions