3

我是在这个级别使用 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了几次,停止并重新启动服务器,关闭并重新打开终端只是为了确保它不是那些东西,但是当我这样做时:

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. 为什么 :name、:position 和 :visible 没有出现在表格中?
  2. 我现在如何添加它们?
4

2 回答 2

1

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

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

你有几个选择:

  1. 如果您此后未进行其他迁移,请执行 arake 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以对表进行更改进行新的迁移。

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

希望这可以帮助!

于 2012-12-11T21:50:32.547 回答
0

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

试试这个;

rails g migration add_position_to_action_figures position:integer visible:boolean

bundle exec rake db:migrate
于 2012-12-11T21:51:43.030 回答