开发者

RoR scaffold add field after script/generate

开发者 https://www.devze.com 2023-01-08 14:20 出处:网络
I generated a scaffold and put in the type:value but now I need to add another field / db column how do I add another type:value without destroying and restarting my whole project?

I generated a scaffold and put in the type:value but now I need to add another field / db column how do I add another type:value without destroying and restarting my whole project?

rake aborted!
Mysql::Error: You have an error in your SQL syntax; check the manual that corres
ponds to your MySQL server version for the right syntax to use near '(11), `titl
e` varchar(255) DEFAULT NULL, `artist_old` varchar(255) DEFAULT NULL,' at line 1
: CREATE TABLE `albums` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY(11
), `title` varchar(255) DEFAULT NULL, `artist_old` varchar(255) DEFAULT NULL, `r
elease_date` datetime DEFAULT NULL, `genre` varchar(255) DEFAULT NULL, `feature`
 int(11) DEFAULT开发者_如何学Go NULL, `image_path` varchar(255) DEFAULT NULL, `created_at` date
time DEFAULT NULL, `updated_at` datetime DEFAULT NULL, `artist_id` int(11) DEFAU
LT NULL) ENGINE=InnoDB


usually when you use the scaffold command it will create a migration in your db/migrate/ folder, containing all the database setup for your model, for example:

class CreateComments < ActiveRecord::Migration
  def self.up
    create_table :comments do |t|
      t.text :body
    end
  end

  def self.down
    drop_table :comments
  end
end

If you have not successfully run the rake db:migrate command after you created the scaffold, you can just easily edit the migration file under db/migrate/ and add the field you missed in the beginning. After you edited the file, run the rake db:migrate command to apply the migration to your database.

If you already stepped through rake db:migrate after creating your scaffold, you can create a new migration with script/generate migration AddSubjectColumnToComments to add another field to your table. In my example above, I would get a new migration and fill in the following code:

class AddSubjectColumnToComments < ActiveRecord::Migration
  def self.up
    add_column :subject, :comments, :string
  end

  def self.down
    remove_column :subject, :comments
  end

Good luck migrating!


Just generate migration and update your views manually.

0

精彩评论

暂无评论...
验证码 换一张
取 消