NoMethodError undefined method 'title' の対処 rake db:migrate:reset

開発環境
OS X 10.9.5
Ruby 2.1.3
Rails 4.2.0

articles/new にアクセスしたところ

undefined method `title' 

というNoMethodErrorが出た。

結論は、「テーブル構造を確認しましょう」です。

環境は

# app/view/articles/new.html.slim

.container
  .row
    .col-md-12
      .box
        = render partial: 'articles/form', locals: { article: @article }
# app/view/articles/_form.html.slim

= form_for article, html: { multipart: true, class: 'form-horizontal' } do |f|
  - if article.errors.any?
    - article.errors.full_messages.each do |message|
      .alert.alert-danger= message

  .form-group
    = f.label :title, class: 'control-label col-md-2'
    .col-md-10
      = f.text_field :title, placeholder: Article.human_attribute_name(:title), required: true,
        class: 'form-control input-lg'

   # 中略

 .clearfix
    = f.submit t('save'), class: 'btn btn-default pull-right'
# app/controller/articles_controller.rb

class ArticlesController < ApplicationController
  
  def new
    @article = Article.new
  end

   # 中略

end

ググってもそれらしき情報が見つからず。。 何を思ったか、ふとdbのテーブル構造に着目した。

# db/migrate/20150218041435_create_articles.rb

class CreateArticles < ActiveRecord::Migration
  def change
    create_table :articles do |t|
      t.string :title, null: false
      t.string :image, null: false
      t.text :body

      t.timestamps
    end
   end
end

ここはこうなっているのに、

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

「なんで title と image と body のカラムがないんだ...!!」

ググったところ

$ rake db:reset

このコマンドは、db/schema.rb に指定されたテーブル設計にリセットするコマンドらしいのだが、Articleモデルを作った時はカラムの設定をしておらず、後から 2015**.rb に付け加えていたので

# db/schema.rb

ActiveRecord::Schema.define(version: 20150218041435) do

  create_table "articles", force: :true do |t|
    
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end

schema.rbはこのようになっていた。

つまり、「最初はとりあえず rails g model Article -d mysql で作って、カラムは後から付けたそう。」と考えていたにもかかわらず

$ rake db:migrate:reset

とすべきところを

$ rake db:reset

とやって、後から付け足したカラムがしっかり上書きされた気になっていたのが問題だった。

この手のエラーはググってもヒットしにくいのでここに書いておきます。参考になれば。

[ 参考サイト ]

rake db:reset と rake db:migrate:reset の違い | EasyRamble