前提
ユーザ画像の表示を実装しようとしたところ、エラーが出ました。
4ページに表示させたくて部分テンプレートを使って記述したら、内3ページに以下のエラーが出ました。残り1ページは思うように表示されました。
一旦テンプレートの呼び出しを消して、とにかく画像だけでも表示させようと
<%= image_tag @user.get_profile_image(100,100) %>
と記述してみても同じエラーが出ました。
テンプレートが別の階層にあるのが関係しているのかと思いましたが、同じ階層にあるページもエラーが出ています。
初質問で勝手がわからないので、とにかく必要そうだと思う記述を載せます。不足がありましたら追加します。
回答お待ちしております。よろしくお願いします。
※UserモデルとBookモデルを作りアソシエーションしています。
※共通テンプレートは「@」を外して呼び出すときに
<%= render 'user_info', user: @user %>
としました。
実現したいこと
- ページにユーザ画像を表示させたい
発生している問題・エラーメッセージ
NoMethodError in Books#index undefined method `get_profile_image' for nil:NilClass
うまく表示されたページ(/users/show.html.erb)
ruby
1<%= image_tag @user.get_profile_image(100,100) %>
表示できなかったページ(/books/index.html.erb)
#他2つのページ:/users/index /books/show <%= image_tag @user.get_profile_image(100,100) %>
Userモデル
has_many :books, dependent: :destroy has_one_attached :profile_image def get_profile_image(width, height) unless profile_image.attached? file_path = Rails.root.join('app/assets/images/no_image.jpg') profile_image.attach(io: File.open(file_path), filename:'default-image.jpg', content_type: 'image/jpeg') end profile_image.variant(resize_to_limit: [width, height]).processed end
Bookモデル
belongs_to :user
Userコントローラ
class UsersController < ApplicationController def show @user = User.find(params[:id]) @books = @user.books end def edit @user = User.find(params[:id]) end def index @users = User.all end def update @user = User.find(params[:id]) @user.update(user_params) redirect_to user_path(@user.id) end private def user_params params.require(:user).permit(:name, :introduction, :profile_image) end end
Bookコントローラ
class BooksController < ApplicationController def show @book = Book.find(params[:id]) end def index @books = Book.all end def new @book = Book.new end def edit @book = Book.find(params[:id]) end def create @book = Book.new(book_params) @book.user_id = current_user.id @book.save redirect_to book_path(@book.id) end def update @book = Book.find(params[:id]) @book.update(book_params) redirect_to book_path(@book.id) end def destroy @book = Book.find(params[:id]) @book.destroy redirect_to books_path end private def book_params params.require(:book).permit(:title, :body) end end
ルーティング
devise_for :users root to: "homes#top" get "/homes/about" => "homes#about", as: "about" resources :users, only: [:show, :edit, :index, :update] resources :books, only: [:show, :edit, :index, :new, :update, :destroy, :create]
試したこと
・共通テンプレートでエラーが出たのでビューに直接記述てみました
・共通部分以外の記述(Bookの一覧表示など)は思う通りに表示されました
・記述ミスがないか何度か見直しました

回答1件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
また依頼した内容が修正された場合は、修正依頼を取り消すようにしましょう。
2022/08/08 06:29
2022/08/08 06:47 編集
2022/08/08 06:47
2022/08/08 07:07