undefined method `get_profile_image' for nil:NilClassを解決したいです。
投稿一覧画面(index.html.erb)でアソシエーションを用いて、
投稿をした人のプロフィール画像をActiveStorageを用いて表示したいのですが
undefined method `get_profile_image' for nil:NilClassというエラーが出て表示出来ません。
発生している問題・エラーメッセージ
NoMethodError in Books#index
Showing /home/ec2-user/environment/bookers2/app/views/books/index.html.erb where line #36 raised:
undefined method `get_profile_image' for nil:NilClass
Extracted source (around line #36):
Rails
1<%# ユーザーのプロフィール画像を下記で表示しようとするとundefined method `get_profile_image' for nil:NilClass %> 2<%= image_tag book.user.get_profile_image %> 3
Rails.root: /home/ec2-user/environment/bookers2
Application Trace | Framework Trace | Full Trace
app/views/books/index.html.erb:36
app/views/books/index.html.erb:33
Request
Parameters:
None
Toggle session dump
Toggle env dump
Response
Headers:
None
該当のソースコード
books/index.html.erb(エラーが出ているページ)
Rails
1<% if @book.errors.any? %> 2 <%= @book.errors.count %>errors prohibited this obj from being saved: 3 <% @book.errors.full_messages.each do |message| %> 4 <%= message %> 5 <% end %> 6<% end %> 7 8<h1>User info</h1> 9<%= image_tag @user.get_profile_image %> 10<%= @user.name %> 11<%= @user.introduction %> 12 13<%= link_to "user_edit", edit_user_path(@user) %> 14 15<h1>New book</h1> 16 17<%= form_with model:@book, local:true do |f| %> 18 19<p>Title</p> 20<%= f.text_area :title %> 21 22<p>Opinion</p> 23<%= f.text_area :body %> 24 25<%= f.submit 'Create Book' %> 26 27<% end %> 28 29<h1>Books</h1> 30<% @books.each do |book| %> 31 32<%# ユーザーのプロフィール画像を下記で表示しようとするとundefined method `get_profile_image' for nil:NilClass %> 33<%= image_tag book.user.get_profile_image %> 34 35 36 <%= link_to book_path(book.id) do %> 37 <%= book.title %> 38 <% end %> 39 40 <%= book.body %> 41<% end %>
books_controller.rb
Rails
1class BooksController < ApplicationController 2 3 before_action :correct_user, only: [:edit, :update] 4 5def create 6 @book = Book.new(book_params) 7 @book.user_id = current_user.id 8 9 10 if @book.save 11 flash[:notice]="You have updated user successfully." 12 redirect_to book_path(@book.id) 13 else 14 @books =Book.all 15 @user = current_user 16 render :index 17 end 18end 19 20def show 21 @book = Book.find(params[:id]) 22 @book_new = Book.new 23end 24 25def index 26 @books = Book.all 27 @book = Book.new 28 @user = current_user 29end 30 31def edit 32 @book = Book.find(params[:id]) 33end 34 35def destroy 36 book = Book.find(params[:id]) 37 book.destroy 38 redirect_to books_path 39end 40 41def update 42 @book = Book.find(params[:id]) 43 @book.user_id = current_user.id 44 45 if @book.update(book_params) 46 flash[:notice] = "You have updated user successfully." 47 redirect_to book_path(book.id) 48 else 49 render :edit 50 end 51end 52 53private 54 55 def book_params 56 params.require(:book).permit(:title, :body) 57 end 58 59 60 61 def correct_user 62 @book = Book.find(params[:id]) 63 @user = @book.user 64 redirect_to(books_path) unless @user == current_user 65 end 66end 67
book.rb
Rails
1class Book < ApplicationRecord 2 belongs_to :user 3 validates :title, presence: true 4 validates :body, length: {maximum: 200}, presence: true 5end 6
user.rb
Rails
1class User < ApplicationRecord 2 # Include default devise modules. Others available are: 3 # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable 4 devise :database_authenticatable, :registerable, 5 :recoverable, :rememberable, :validatable 6 7 has_many :books, dependent: :destroy 8 has_one_attached :profile_image 9 10 validates :name, {length: {in: 2..20} } 11 12 validates :name, uniqueness: true 13 14 validates :introduction, {length: {maximum: 50}} 15 16 17 18 19 def get_profile_image 20 if profile_image.attached? 21 profile_image 22 else 23 'no_image.jpg' 24 end 25 end 26end 27
users/show.html.erb
(こちらの記述では投稿したユーザーのプロフィール画像が問題なく表示されている)
Rails
1<h1>User info</h1> 2<div> 3 <%= image_tag @user.get_profile_image %> 4 <h3><%= @user.name %></h3> 5 <h3><%= @user.introduction %></h3> 6 7</div> 8 9<h1>New book</h1> 10<%= form_with model: @book_new, local:true do |f| %> 11 12 13<%= f.text_field :title %> 14 15 16<%= f.text_area :body %> 17 18 19<%= f.submit "Create Book" %> 20 21<% end %> 22 23 24<h1>Books</h1> 25<% @books.each do |book| %> 26<%= image_tag book.user.get_profile_image %> 27<%= link_to book_path(book.id) do %> 28 <%= book.title %> 29 <% end %> 30 <p><%= book.body %></p> 31<% end %> 32
users_controller.rb
Rails
1class UsersController < ApplicationController 2 3 4 before_action :correct_user, only: [:edit, :update] 5 6 def show 7 @book_new = Book.new 8 @user = User.find(params[:id]) 9 10 #bookだとエラーが出た 11 @books = @user.books 12 end 13 14 def index 15 @user = current_user 16 @users = User.all 17 @book_new = Book.new 18 end 19 20 def edit 21 @user = User.find(params[:id]) 22 end 23 24 def update 25 @user = User.find(params[:id]) 26 if @user.update(user_params) 27 flash[:notice] = "You have updated user successfully." 28 redirect_to user_path(user.id) 29 else 30 render :edit 31 end 32 end 33 34 private 35 36 def user_params 37 params.require(:user).permit(:name, :introduction, :profile_image) 38 end 39 40 def correct_user 41 @user = User.find(params[:id]) 42 if current_user != @user 43 redirect_to user_path(@user) 44 end 45 end 46 47end
ターミナル
Rails
1Started GET "/books" for 14.133.239.112 at 2021-12-12 12:42:12 +0000 2Cannot render console from 14.133.239.112! Allowed networks: 127.0.0.0/127.255.255.255, ::1 3 (0.4ms) SELECT sqlite_version(*) 4 (0.1ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC 5Processing by BooksController#index as HTML 6 User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 1], ["LIMIT", 1]] 7 Rendering layout layouts/application.html.erb 8 Rendering books/index.html.erb within layouts/application 9 ActiveStorage::Attachment Load (0.1ms) SELECT "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_id" = ? AND "active_storage_attachments"."record_type" = ? AND "active_storage_attachments"."name" = ? LIMIT ? [["record_id", 1], ["record_type", "User"], ["name", "profile_image"], ["LIMIT", 1]] 10 ↳ app/models/user.rb:24:in `get_profile_image' 11 ActiveStorage::Blob Load (0.1ms) SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]] 12 ↳ app/views/books/index.html.erb:9 13 Book Load (0.1ms) SELECT "books".* FROM "books" 14 ↳ app/views/books/index.html.erb:33 15 User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 4], ["LIMIT", 1]] 16 ↳ app/views/books/index.html.erb:36 17 Rendered books/index.html.erb within layouts/application (Duration: 48.5ms | Allocations: 24166) 18 Rendered layout layouts/application.html.erb (Duration: 48.7ms | Allocations: 24241) 19Completed 500 Internal Server Error in 96ms (ActiveRecord: 2.4ms | Allocations: 39498) 20 21 22 23ActionView::Template::Error (undefined method `get_profile_image' for nil:NilClass): 24 33: <% @books.each do |book| %> 25 34: 26 35: <%# ユーザーのプロフィール画像を下記で表示しようとするとundefined method `get_profile_image' for nil:NilClass %> 27 36: <%= image_tag book.user.get_profile_image %> 28 37: 29 38: 30 39: <%= link_to book_path(book.id) do %> 31 32app/views/books/index.html.erb:36 33app/views/books/index.html.erb:33 34
試したこと
1 エラー文から、bookが空→@booksが空だと思い、indexアクションで@booksが定義されているか確認しました。
2 get_profile_imageをbook.rbにも記述してみましたが解決には至らなかったです。
補足情報(FW/ツールのバージョンなど)
ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-linux]
Rails 6.1.4.1
以上、よろしくお願いいたします。
回答1件
あなたの回答
tips
プレビュー