Search code examples
ruby-on-rails-3rails-migrationsmysql2mysql

Rails3 Mysql2::Error: Unknown column - ActiveRecord::StatementInvalid


I'm new to working with databases in Rails at this level, and I've looked for several hours but haven't found a solution to this specific problem.

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

Error:

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

Extracted source (around line #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>

I generated the ActionFigures model and controller, but specified :position, :name, etc. later in the migration file:

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

And this in the model:

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

I've run rake db:migrate several times already, stopped and restarted the server, closed and reopened Terminal just to be sure it wasn't those things, but when I do:

mysql> SHOW FIELDS FROM action_figures;

I get the following table:

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

Questions:

  1. Why are :name, :position, and :visible not showing up in the table?
  2. How to I add them now?

Solution

  • Did you add the table ... run the migrations .. and then edit the migration file to add position and visible attributes? If so, you'll need to add a new migration (or rerun the last migration)

    Try this;

    rails g migration add_position_to_action_figures position:integer visible:boolean
    
    bundle exec rake db:migrate