【问题标题】:migration fails in Rails with some SQL error在 Rails 中迁移失败并出现一些 SQL 错误
【发布时间】:2013-06-11 06:01:55
【问题描述】:

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

【问题讨论】:

  • 您的迁移类绝对不应与您的 User 模型命名相同。
  • @Deefour :如果我删除 User.create 行,那么创建表就可以正常工作
  • 我只是指出您遇到问题的原因。迁移将在没有模型实例化的情况下运行,因为您不再引用不存在的类方法。
  • @Deefour :那么我可以从 User 中将迁移类命名为“Users”吗??
  • 我建议阅读有关该主题的Rails Guide。您的迁移应该更恰当地命名为 CreateUsers 或类似名称。就目前而言,您的 User 迁移类与您的 User 模型类存在命名冲突。

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1 ruby-on-rails-3.2


【解决方案1】:

使用 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中

【讨论】:

  • 不想使用脚手架
【解决方案2】:

迁移代码:

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 具有“种子”功能,可用于为数据库播种初始数据。这是一个非常简单的功能:只需用一些 Ruby 代码填充 db/seeds.rbrun rake db:seed

所以你只需删除创建语句,你的迁移代码应该是这样的:

 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 以提供数据库表:

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

User.create(用户)

然后运行: rake db:seed

【讨论】:

    猜你喜欢
    • 2021-10-20
    • 2020-05-13
    • 1970-01-01
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    • 2017-07-16
    • 1970-01-01
    相关资源
    最近更新 更多