seedデータの変更は削除する必要がある!

ハマったエラーについて書いていきます

 

  • エラー時の状況

CRUD処理実装と'devise' gemでログイン処理を実装後に、localhost:3000で入ると

undefined method 'id' for nil:Nil Class

というエラーが出る

 

この時の主なコードはこちら

  • ルート

Rails.application.routes.draw do

  root to: 'posts#index'

  devise_for :users

   resources :posts

   resources :users, only: :show

end

  • コントローラ

Postsコントローラ

class PostsController < Application Controller

  before_action :move_to_index, except: :index

  

  def index

    @posts = Post.all

  end

 

  def new

    @post = Post.new

  end

 

  def create

    Post.create(content: post_params[:content], user_id: current_user.id)

  end

 

  def move_to_index

    redirect_to action: :index unless user_signed_in?

  end

 

  private

  def post_params

     params.require(:post).permit(:content)

  end

end

Usersコントローラ

class UsersController < ApplicationController

  def show

    @user =  User.find(current_user.id)

  end

end

  • モデル

post.rb

class Post < ApplicationRecord

  belongs_to :user

end

user.rb

 class User < ApplicationRecord

    devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  has_many :posts

end

  • ビュー

views/posts/index.html.erb

<h1>投稿一覧</h1>
<% if user_signed_in? %>
  <% @posts.each do |post| %>
    <p><%= post.content %>:会員No.<%= post.user.id%></p>
  <% end %>
<% else %>
  <p>ログインしてください</p>
<% end %>

  • データベース(sqlite3)

postsテーブル

class CreatePosts < ActiveRecord::Migration[5.2]
  def change
    create_table :posts do |t|
      t.text :content
      t.integer :user_id


      t.timestamps
    end
  end
end

  • seed

Post.create(content: "熱rjrhje狂のWebマrhjerjhjーケティンsprnhグ", user_id: 1)
Post.create(content: "g熱rjrhjhグ", user_id: 2)
Post.create(content: "ehrehンsprnhグ", user_id: 3)
Post.create(content: "gnrnbn熱rjrhje狂のW", user_id: 4)

以上です

 

結果から言うと、問題があったのはseedの部分とデータベースです(コントローラやビュー等には問題無し)

 

エラーの原因はデータベーステーブルに登録されているカラムは:contentと:user_idなんですが、postモデルを作成した時に:user_idカラムを入れ忘れて後からadd_column で追加したんですけど、その間にseeds.rbで上記のデータを入れた為に:contentのみで:user_idが無いデータを作成した事になっていて、追加後にもう一度

bundle exec rake db:seed

で入れ直した時に前のデータは消えて新しいデータのみになると思ったところ、古いデータに新しいデータが追加され存在しカラム無しの古いデータが読み込めないからNo Method Error NilClassが出たようです。

 

今回の解決方法は既存のseedデータを修正した場合、前のデータがエラーの原因になっていて消す必要があるためRails Controllerで

Post.delete_all

でデータを削除後に

bundle exec rake db:seed

でデータを入れ直すことで正しいデータのみが残りエラーが解決しました!

 

追記

seedデータによく変更を加える場合は

rails db:migrate:reset db:seed

でデータベースの削除&作成を一度で出来るそうです!