簡體   English   中英

Rails3 Mysql2 ::錯誤:未知列 - ActiveRecord :: StatementInvalid

[英]Rails3 Mysql2::Error: Unknown column - ActiveRecord::StatementInvalid

我剛接觸在這個級別的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. 為什么:名稱,:位置和:可見未顯示在表格中?
  2. 我現在如何添加它們?

如果您在舊的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以對表進行更改。

還有其他方法,但根據您在數據庫中的數據,我會選擇2或3。

希望這可以幫助!

您是否添加了表...運行遷移..然后編輯遷移文件以添加位置和可見屬性? 如果是這樣,您將需要添加新遷移(或重新運行上次遷移)

嘗試這個;

rails g migration add_position_to_action_figures position:integer visible:boolean

bundle exec rake db:migrate

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM