前提
本のタイトルと感想を投稿できるアプレイケーションを作っています。
実現したいこと
- UserのIndexページに部分テンプレート+ユーザーの一覧を表示させたい
発生している問題・エラーメッセージ
NoMethodError in UsersController#index undefined method `profile_image' for nil:NilClass
該当のソースコード
ruby(users_controller.rb)
1 @users = @user.profile_image 2
試したこと
showのコントローラだとこれでうまくいっていたので同じようにしたところ今回のエラーが出ました。
補足情報(FW/ツールのバージョンなど)
ruby(users/_user.html.erb)
1 <div> 2 <h1>User info</h1> 3 <%= image_tag user.get_profile_image(100,100) %><br> 4 <h3>name <%= user.name %></h3> 5 <h3>introduction <%= user.user_introduction %></h3> 6 <p><%= link_to "プロフィール編集", edit_user_path(user) %></p> 7 </div> 8 9 <div> 10 <h1>New book</h1> 11 <%= form_with model: book do |f| %> 12 <p>Title</p><%= f.text_field :title %> 13 <p>Opinion</p><%= f.text_area :body %> 14 <br><%= f.submit 'Create Book' %> 15 <% end %> 16 </div>
ruby(users_controller.rb)
1class UsersController < ApplicationController 2 before_action :correct_user, only: [:edit, :update] 3 def show 4 @user = User.find(params[:id]) 5 @book = Book.new 6 @users = @user.profile_image 7 @books = @user.books 8 end 9 10 def edit 11 @user = User.find(params[:id]) 12 end 13 14 def index 15 @users_list = User.all 16 @users = @user.profile_image 17 @user = current_user 18 @book_new = Book.new 19 end 20 21 def update 22 @user = User.find(params[:id]) 23 @user.update(user_params) 24 redirect_to user_path(@user.id) 25 end 26 27 private 28 29 def correct_user 30 user = User.find(params[:id]) 31 if current_user.id != user.id 32 redirect_to user_path(current_user.id) 33 end 34 end 35 36 def user_params 37 params.require(:user).permit(:name, :profile_image, :user_introduction) 38 end 39 40end 41
ruby(models/user.rb)
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 def get_profile_image(width, height)#ユーザーアイコン設定# 11 unless profile_image.attached? 12 file_path = Rails.root.join('app/assets/images/sample-author1.jpg') 13 profile_image.attach(io: File.open(file_path), filename: 'default-image.jpg', content_type: 'image/jpeg') 14 end 15 profile_image.variant(resize_to_limit: [width, height]).processed 16 end 17end 18
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/08/12 04:07
2022/08/12 04:42
2022/08/13 12:32