2

我是 Rails 的初学者,使用 Rails 的迁移将行插入数据库时​​遇到问题。

class Actions < ActiveRecord::Migration
  def up
    create_table :actions do |t|
      t.integer :channel_id
      t.string :name
      t.text :description
      t.integer :weight

      t.timestamps
    end

    add_index :actions, :channel_id

    Actions.create :name => 'name', :description => '', :weight => 1, :channel_id => 1
  end

运行此代码会导致:

==  Actions: migrating ========================================================
-- create_table(:actions)
   -> 0.0076s
-- add_index(:actions, :channel_id)
   -> 0.0036s
-- create({:name=>"name", :description=>"", :weight=>1, :channel_id=>1})
rake aborted!
An error has occurred, this and all later migrations canceled:

SQLite3::SQLException: unrecognized token: "{": {:name=>"name", :description=>"", :weight=>1, :channel_id=>1}

动作模型:

class Actions < ActiveRecord::Base
  belongs_to :channels
  attr_accessible :name, :description, :weight, :channel_id
end

我不知道大括号来自哪里以及它们为什么会导致异常。谁能帮我解决这个问题?

4

1 回答 1

3

哦,看来您的迁移类名称与您尝试访问的模型的名称相同( Actions)。因此,将在迁移类上调用该方法而不是模型类,该create方法可能会尝试使用您的哈希或其他东西创建一个表。这就是您收到该错误消息的原因。

重命名您的迁移类(以及为了一致性起见的文件),它应该可以正常运行:

class CreateActions < ActiveRecord::Migration
于 2012-07-10T20:27:20.727 回答