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?
1 Answer
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
3 Comments
Jay
Can I directly modify the existing migration .rb file? Or do I have to use the rails migrate command?
class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :fullname, :limit => 50 t.string :email t.string :postalcode t.timestamps end end endCharlie Martin
If you modify and re-run the existing, you will have to revert whatever other changes are in the existing migration or it will try to do them again. The proper rails way of doing this is to create a new migration. This would be especially crucial if you were working with a team of developers who all needed to make the change. If you only have one migration and you prefer to edit it and drop and recreate your database, then that will work fine
Jay
Thanks for the insightful comment. I'll have to read more about best practices on migration. I only have a single migration file at the moment.