Ruby on Rails: adding columns to existing database

前端 未结 7 712
Happy的楠姐
Happy的楠姐 2021-01-30 07:49

I\'m getting an error:

SQLite3::SQLException: no such column: ideas.list_id: 
SELECT \"ideas\".* FROM \"ideas\"  
WHERE \"ideas\".\"list_id\" = 2
相关标签:
7条回答
  • 2021-01-30 07:57

    You can also do this ..

    rails g migration add_column_to_users list_id:string

    then rake db:migrate

    also add :list_id attribute in your user controller ;

    for more detail check out http://guides.rubyonrails.org/active_record_migrations.html

    0 讨论(0)
  • 2021-01-30 08:06

    If you already have files in your migrate folder, you could just add column you want there(just type the code), delete development.sqlite or whatever represents your db file, and run rake db:migrate. It will then create a new sqlite file with new column in table, and you can check it in schema.rb

    So, basically, everything you did seems good, except you didn't delete your database file. Doing this seems the easiest for me, all though you will lose all the files in your database. If you're just testing and developing Rails app, this works. Can anyone comment if there is something wrong with this approach, besides what i wrote?

    Edit: I actually found an answer about that here Editing Existing Rails Migrations is a good idea?

    0 讨论(0)
  • 2021-01-30 08:10

    You should not add new rows to old migrations. Migration is a step of building database. And number of last executed migration is stored in schema, and it will not be run or redone if you use will use rake db:migrate. If you run the migration with creating the table before, then you should create new migration where you may use add_column method.

    0 讨论(0)
  • 2021-01-30 08:12

    Rails 4.0 easy way to add single or multiple column https://gist.github.com/pyk/8569812

    0 讨论(0)
  • 2021-01-30 08:14

    If you want to add a new column to an exist database, you should use rails generate migration. So you can try rails generate migration add_list_id_to_ideas list_id:integer and then use rake db:migrate to commit this change.

    0 讨论(0)
  • 2021-01-30 08:15

    migration file name has the datetime encoded in its name so rails run this migration one and do not run it again unless you do a rollback

    and here come the magic of migration to build you db with small steps so no need to update a migration after run rake db:migrate , you should make a new migration to do the change you want to your db schema

    and remember to

    remove the added line form the old migration file as it might raise errors if you decided to rollback this migration

    0 讨论(0)
提交回复
热议问题