简体   繁体   中英

Rails generate migration not working

I've got below command run on console

rails g migration payslips first_name:string last_name:string

But this just generates empty file like below

class Payslips < ActiveRecord::Migration
  def change
  end
end

I cannot find the reason why. Is there something wrong with the console generate command?

Is correct functionality, if you want create a model then you need run:

rails g model payslips first_name:string last_name:string

Then you get:

class CreatePayslips < ActiveRecord::Migration
  def change
    create_table :payslips do |t|
      t.string :first_name
      t.string :last_name

      t.timestamps
    end
  end
end

Assuming that your model has been created , you must be more explicit when explaining what you really want to do :

rails g migration add_first_name_and_last_name_to_payslips first_name:string last_name:string

The above tells the migrator to add first_name and last_name to the payslips table, so you end up with this migration :

class AddFirstNameAndLastNameToPayslips < ActiveRecord::Migration
  def change
    add_column :payslips, :first_name, :string
    add_column :payslips, :last_name, :string
  end
end

Use the word: Create before your table name.

$ rails generate migration CreateProducts name:string part_number:string

generates:

class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.string :name
      t.string :part_number
    end
  end
end

source: http://guides.rubyonrails.org/migrations.html

You can generate migration alone to modify the tables. But to create new table you have to generate model so that it will generate create table migration for the corresponding model(like @efrenfuentes said)

Or you can try what you want to do with a plugin called migration_for

rails plugin install git://github.com/capotej/migration_for.git

rails g migration_for create_table:payslips add_column:payslips:first_name:string add_column:payslips:last_name:string

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