質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.46%
Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Q&A

解決済

1回答

1314閲覧

画像投稿でのnil:NilClass

退会済みユーザー

退会済みユーザー

総合スコア0

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

0グッド

0クリップ

投稿2021/07/27 04:21

編集2021/07/27 08:42

実現したいこと

railsにてwebアプリ作成中です。

画像の投稿(アップロード)をしたいのですが、
画像は該当のファイル(app/assets/images/posts/#{@post.image_photo}")に保存はされているものの、
表示されず下記のエラーがでてしまいます。

エラーで検索してみましたが原因が特定できませんでした。。
何か原因などわかる方いましたらコメントよろしくお願い致します。。

発生しているエラーメッセージ

NoMethodError in PostsController#create **undefined method `read' for nil:NilClass** Extracted source (around line #24): 22 @post.image_photo="#{@post.id}.jpg" 23 image=params[:image_photo] 24 File.binwrite("app/assets/images/posts/#{@post.image_photo}", image.read) 25 redirect_to("/posts/#{@post.id}") 26 else 27 render("/posts/new")

該当のソースコード

html

1**posts/new.html** 2<div class="main posts-new"> 3 <div class="container"> 4 <h1 class="form-heading">投稿画面</h1> 5 6 <%= form_with(model: @post, local: true) do |s| %> 7 8 <p>メイン写真(コーディネート写真)</p> 9 <label for="file_photo"> 10 <%= s.file_field :image_photo %> 11 </label><br> 12 <div class="msr_text_05"> 13 <label>タイトル</label> 14 <%= s.text_field :image_title %><br> 15 </div> 16 <div class="msr_text_05"> 17 <label>説明</label> 18 <%= s.text_field :description %> 19 </div> 20 <div class="parents"> 21 <%= s.fields_for :items do |t| %> 22 <%= render "posts/items_fields", f: t %> 23 <% end %> 24 <div class="links"> 25 <%= link_to_add_association "+アイテム入力フォーム追加", s, :items, partial: 'items_fields' %> 26 </div> 27 </div><br> 28 <div class="actions"> 29 <input type="submit" value="投稿"> 30 </div> 31 <% end %> 32 <br> 33 <%= link_to("トップページへ戻る", "/") %> 34 </div> 35</div>

html

1**posts/show.html** 2<div class="main posts-show"> 3 <div class="container"> 4 <div class="posts-show-item"> 5 <%= link_to(@user.name, "/users/#{@user.id}") %> 6 <p> 7 <%= image_tag "posts/#{@post.id}", width: '700px', height: '400px' %> 8 </p> 9 <p> 10 <%= @post.image_title %> 11 </p> 12 <p> 13 <%= @post.description %> 14 </p> 15 16 <%= form_tag("/items/new") do %> 17 <p><span>アイテム名</span> 18 <%= @post.products_name %> 19 </p> 20 <p><span>ブランド</span> 21 <%= @post.brand %> 22 </p> 23 <p><span>サイズ</span> 24 <%= @post.size %> 25 </p> 26 <p><span>&yen;</span> 27 <%= @post.price %> 28 </p> 29 <% end %> 30 31 <div class="post-time"> 32 <%= @post.created_at.strftime("%Y-%m-%d") %> 33 </div> 34 <% if @post.user_id == @current_user.id %> 35 <div class="post-menus"> 36 <%= link_to("編集", "/posts/#{@post.id}/edit") %> 37 <%= link_to("削除", "/posts/#{@post.id}/destroy", {method: "post"}) %> 38 </div> 39 <% end %> 40 </div> 41 </div> 42 <%= link_to("トップページへ", "/") %> 43</div>

html

1**PostsController** 2class PostsController < ApplicationController 3 before_action :ensure_correct_user, {only: [:edit, :update, :destroy]} 4 5 def index 6 @posts = Post.all.order(created_at: :desc) 7 end 8 9 def show 10 @post = Post.find_by(id: params[:id]) 11 @user = @post.user 12 end 13 14 def new 15 @post = Post.new 16 @post.items.build 17 end 18 19 def create 20 @post = Post.new(post_params) 21 @post.user_id = @current_user.id 22 if @post.save 23 @post.image_photo="#{@post.id}.jpg" 24 image=params[:image_photo] 25 File.binwrite("app/assets/images/posts/#{@post.image_photo}", image.read) 26 redirect_to("/posts/#{@post.id}") 27 else 28 render("/posts/new") 29 end 30 31 32 end 33 34 def edit 35 @post = Post.find_by(id: params[:id]) 36 end 37 38 def update 39 @post = Post.find_by(id: params[:id]) 40 @post.image_title = params[:image_title] 41 @post.price = params[:price] 42 @post.image_photo="#{@post.id}.jpg" 43 image=params[:image_photo] 44 File.binwrite("app/assets/images/posts/#{@post.image_photo}", image.read) 45 if @post.save 46 redirect_to("/posts/#{@post.id}") 47 else 48 render("posts/#{@post.id}/edit") 49 end 50 end 51 52 def destroy 53 @post = Post.find_by(id: params[:id]) 54 @post.destroy 55 redirect_to("/") 56 end 57 58 def ensure_correct_user 59 @post = Post.find_by(id: params[:id]) 60 if @post.user_id != @current_user.id 61 flash[:notice] = "権限がありません" 62 redirect_to("/posts/index") 63 end 64 end 65 66 private 67 68 def post_params 69 params.require(:post).permit(:image_photo, :image_title, :description, items_attributes: [:item_image, :products_name, :brand, :size, :price]) 70 end 71end 72

追記

log

1##### log 2 3Started POST "/posts" for 172.23.0.1 at 2021-07-27 04:53:14 +0000 4Cannot render console from 172.23.0.1! Allowed networks: 127.0.0.0/127.255.255.255, ::1 5Processing by PostsController#create as HTML 6Parameters: {"authenticity_token"=>"Fzd0AqvM5+OLg8/Dy4WdfYraF7hjMvBxrMckycOMuxOyHlatXvlhq96CgvRYL7Fnmp7E+6VPlqUp1tfULrlRgA==", "post"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x00007efcc96dbbc8 @tempfile=#<Tempfile:/tmp/RackMultipart20210727-1-wwif4s.jpeg>, @original_filename="キャンプテントのアイコン素材.jpeg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"post[image]\"; filename=\"\xE3\x82\xAD\xE3\x83\xA3\xE3\x83\xB3\xE3\x83\x95\xE3\x82\x9A\xE3\x83\x86\xE3\x83\xB3\xE3\x83\x88\xE3\x81\xAE\xE3\x82\xA2\xE3\x82\xA4\xE3\x82\xB3\xE3\x83\xB3\xE7\xB4\xA0\xE6\x9D\x90.jpeg\"\r\nContent-Type: image/jpeg\r\n">, "image_title"=>"い", "description"=>"い", "items_attributes"=>{"0"=>{"products_name"=>"い", "brand"=>"い", "size"=>"い", "price"=>"い", "_destroy"=>"false"}}}} 7User Load (0.8ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 5 LIMIT 1 8↳ app/controllers/application_controller.rb:14:in `set_current_user' 9Unpermitted parameter: :_destroy 10CACHE User Load (0.0ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 5 LIMIT 1 [["id", 5], ["LIMIT", 1]] 11↳ app/models/post.rb:11:in `user' 12(0.5ms) BEGIN 13↳ app/controllers/posts_controller.rb:21:in `create' 14Post Create (1.3ms) INSERT INTO `posts` (`created_at`, `updated_at`, `description`, `image_title`, `image`, `user_id`) VALUES ('2021-07-27 04:53:14.247719', '2021-07-27 04:53:14.247719', 'い', 'い', '#<ActionDispatch::Http::UploadedFile:0x00007efcc96dbbc8>', 5) 15↳ app/controllers/posts_controller.rb:21:in `create' 16Item Create (0.7ms) INSERT INTO `items` (`brand`, `size`, `price`, `products_name`, `created_at`, `updated_at`, `post_id`) VALUES ('い', 'い', 0, 'い', '2021-07-27 04:53:14.262827', '2021-07-27 04:53:14.262827', 62) 17↳ app/controllers/posts_controller.rb:21:in `create' 18(2.0ms) COMMIT 19↳ app/controllers/posts_controller.rb:21:in `create' 20Completed 500 Internal Server Error in 46ms (ActiveRecord: 5.2ms | Allocations: 6830) 21NoMethodError (undefined method `read' for nil:NilClass): 22app/controllers/posts_controller.rb:24:in `create' 23

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

undefined method `read' for nil:NilClass

readというメソッドが存在しない、といってます
そのimageがnilになってるんでは。
なにが入ってるのかチェックしてみよう

投稿2021/07/27 04:24

y_waiwai

総合スコア87800

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

退会済みユーザー

退会済みユーザー

2021/07/28 01:05 編集

ご回答ありがとうございます! logを確認したところnilになっていました。 アドバイスありがとうございました!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.46%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問