0

rake db:migrate 在我的开发服务器上失败,错误是:

Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for
 at line 1: {:username=>"user", :password=>"user"}D:/WorkSpace/Ruby_WorkSPace/SLA_Rails_june10/db/migrate/20130611053608
d:in `migrate'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)

我的迁移代码是:

class User < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.column :username , :string 
      t.column :password , :string
    end
    User.create :username=>"user" ,:password=>"user"
    User.create :username=>"admin" ,:password=>"admin"
  end

  def self.down
    drop_table :users
  end
end

enter code here

我的型号代码是

class User < ActiveRecord::Base
  attr_accessible :username, :password
end
4

2 回答 2

0

使用 rails 命令创建迁移脚本:

rails g scaffold User username:string password:string

该命令将生成以下脚本。然后你可以添加“种子”。

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :username
      t.string :password

      t.timestamps
    end
    User.create(:username=>"user", :password=>"user")
    User.create(:username=>"admin", :password=>"admin")
  end
end

顺便提一下,初始数据应该位于 db/seeds.rb

于 2013-06-11T06:42:50.793 回答
0

迁移代码:

class User < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.column :username , :string 
      t.column :password , :string
    end
    User.create :username=>"user", :password=>"user"
    User.create :username=>"admin",:password=>"admin"
  end

  def self.down
     drop_table :users
  end
end

型号代码:

 class User < ActiveRecord::Base
   attr_accessible :username, :password
 end

在上面的代码中,您正在创建两个用户,同时创建表。

Rails 有一个“种子”功能,应该用于为数据库播种初始数据。这是一个非常简单的功能:只需填写db/seeds.rb一些 Ruby 代码,然后run rake db:seed

因此,您只需删除 create 语句,您的迁移代码应如下所示:

 class User < ActiveRecord::Migration
   def self.up
     create_table :users do |t|
       t.column :username , :string 
       t.column :password , :string
     end
    end

   def self.down
     drop_table :users
   end
 end

创建表后,只需填写您db/seeds.rb的馈送数据库表:

用户 = [{:username=>"user", :password => "user"}, {:username=>"admin", :password => "admin"}]

用户创建(用户)

然后运行: rake db:seed

于 2013-06-11T06:33:22.320 回答