Rails3 Mysql2 ::错误:未知列 - ActiveRecord :: StatementInvalid

时间:2012-12-11 21:42:40

标签: ruby-on-rails-3 rails-migrations mysql2 mysql

我刚接触在这个级别的Rails中使用数据库,我已经找了好几个小时但没有找到解决这个特定问题的方法。

版本: Rails 3.2.9,Ruby 1.9.3,MySQL 5.5.28(mysql2 gem 2.9.0),Mac OS 10.7.5

错误:

ActiveRecord::StatementInvalid in Action_figures#list

Mysql2::Error: Unknown column 'action_figures.position' in 'order clause': SELECT `action_figures`.* FROM `action_figures`  ORDER BY action_figures.position ASC

提取的来源(第14行附近):[list.html.erb]

11:       <th>Visible</th>
12:       <th>Actions</th>
13:     </tr>
14:     <% @action_figures.each do |action_figure| %>
15:     <tr>
16:       <td><%= action_figure.position %></td>
17:       <td><%= action_figure.name %></td>

我生成了ActionFigures模型和控制器,但在迁移文件中指定了:position,:name等

class CreateActionFigures < ActiveRecord::Migration
  def change
    create_table :action_figures do |t|
      t.string "name"
      t.integer "position"
      t.boolean "visible", :default => false
      t.timestamps
    end
  end
end

这在模型中:

class ActionFigure < ActiveRecord::Base
  has_many :pages
  attr_accessible :name, :position, :visible
end

我已经多次运行rake db:migrate,停止并重新启动服务器,关闭并重新打开终端以确保它不是那些东西,但是当我这样做时: < / p>

mysql> SHOW FIELDS FROM action_figures;

我得到下表:

+------------+----------+------+-----+---------+----------------+
| Field      | Type     | Null | Key | Default | Extra          |
+------------+----------+------+-----+---------+----------------+
| id         | int(11)  | NO   | PRI | NULL    | auto_increment |
| created_at | datetime | NO   |     | NULL    |                |
| updated_at | datetime | NO   |     | NULL    |                |
+------------+----------+------+-----+---------+----------------+

问题:

  1. 为什么:名称,:位置和:可见未显示在表格中?
  2. 如何添加它们?

2 个答案:

答案 0 :(得分:1)

如果您在旧的ActionFigures迁移文件db:migrate中指定了位置,名称和其他所有内容,则无法获取该文件中的更改。

如果查看db文件夹中的schema.rb文件,它有一个版本号。该数字与上次运行的迁移文件上的数字相匹配。因此,当您运行rake db:migrate时,它会考虑该数字,因此在此之前不会重新运行迁移。发生这种情况,以便表格不会尝试重新创建等等......

您有几个选择:

  1. 如果您之后没有进行过其他迁移,请执行rake db:rollback以撤消ActionFigure表创建的更改。

  2. 执行rake db:drop然后rake db:createrake db:migrate重新创建包含您在迁移中所做更改的表格。

  3. 删除您在迁移文件中所做的更改,并使用rails g migration add_name_and_position_to_action_figures name position:integer进行新迁移,然后运行rake db:migrate对您的表进行更改。

  4. 还有其他方法,但根据您在数据库中的数据,我会选择2或3。

    希望这有帮助!

答案 1 :(得分:0)

您是否添加了表格...运行迁移..然后编辑迁移文件以添加位置和可见属性?如果是这样,您将需要添加新迁移(或重新运行上次迁移)

试试这个;

rails g migration add_position_to_action_figures position:integer visible:boolean

bundle exec rake db:migrate
相关问题