简体   繁体   中英

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?

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.

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.

You will have to update your database, no matter what (Remember to 'rake db:migrate' after you create the migration!)

Regarding the interface, you are a bit more lucky: the formtastic plugin makes your views look like this:

The 'f.inputs' is calculating the form fields on-the-fly, based on your model's attributes. This will not cover complex forms that need special treatment, but the usual ones, you will get them automatically.

For an easy-to-understand tutorial, see the latest railcast (Railscast #184, you will have to google for it, I can't post 2 links because I'm not cool enough for stackoverflow yet, sorry).

Railcast #185 is supposed to continue covering formtastic, and it's due to be published next monday.

需要手动完成,或者需要重新生成脚手架。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM