Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a field in Ruby on Rails?

I'm new to RoR, and I've just used scaffold to generate a table and create the pages for CRUD operations. Now I want to add a new field to this. One place I found tells me how to do that in the database, but is there a way to do it where it will add the field to all the pages too, or is that just a manual operation and I need to make sure I know all my fields up front?

like image 267
Max Schmeling Avatar asked Oct 22 '09 17:10

Max Schmeling


People also ask

How do you create a field in Ruby?

First you'll write a migration to add the field, run the migration, then you need to rerun the scaffold to regenerate the views, etc. Beware, this will wipe out edited files from before. Of course, instead of scaffolding again you could manually add references to new field where appropriate.


2 Answers

To add a new column to the database

$ script/generate migration add_fieldname_to_tablename fieldname:string 
$ rake db:migrate

To get your views up to date you can run the scaffold again, with your updated list of fields. It will balk on replacing your migrations but you can force it to replace your views.

$ script/generate scaffold tablename fieldname:string old_field_1:string ...

At the prompt answer a and it will overwrite the views, but not the old migration. It also won't modify your existing data.

like image 102
EmFi Avatar answered Oct 03 '22 11:10

EmFi


First you'll write a migration to add the field, run the migration, then you need to rerun the scaffold to regenerate the views, etc. Beware, this will wipe out edited files from before. Of course, instead of scaffolding again you could manually add references to new field where appropriate.

like image 21
Karmen Blake Avatar answered Oct 03 '22 09:10

Karmen Blake