简体   繁体   中英

How do I add a field after I've run rails generate model/scaffold?

Let's say I forgot to add a field to my model. How do I go about adding it cleanly? Do I need to re-run rails generate or can I edit a file somewhere?

Either you should re-run your generate scaffold/model (will blow away existing code)

or you can add the field directly to the database and your view

Rails3: rails generate migration add_column_name_to_table_name column_name:string

or

Rails2.x: ruby script/generate migration addColumnToTableName column_name:string

which will generate a file in db/migrate which you can apply with a 'rake db:migrate'

Then you should modify your views to add the appropriate code to display/edit the new field.

more info: http://railscasts.com/episodes/83-migrations-in-rails-2-0

rails g scaffold Users name:string

If i have to add new field in already generated scaffold,

rails generate migration add_url_to_users url:string

and modify the _form.htm.erb file as

<div class="field">
     <%= f.label :name %><br>
     <%= f.text_field :name %>
</div>

<div class="field">
     <%= f.label :url %><br>
     <%= f.text_field :url %>
</div>

But my problem is I can save name only not url

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