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

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

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

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

Q&A

解決済

1回答

5562閲覧

Railsで画像が保存されない問題の解決方法を探しています(carrierwave及びminimagickを使用)

pontarou3

総合スコア18

Ruby on Rails

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

1グッド

1クリップ

投稿2020/03/12 10:20

編集2020/03/13 07:58

#【現在の状況】Railsで画像添付機能付きミニ掲示板アプリケーションを作成しています。

準備段階としてgemにて
carrierwave
minimagick

を用意。bundle install済みです。

#【解決したいこと】画像の投稿だけDBに保存されません

できる◯
タイトル、コンテンツの投稿

できない×
画像の投稿
title、contentと画像の投稿

(バリデーションは現在かけていません)

#paramsのメッセージについて

42: private 43: 44: def post_params 45: params.require(:post).permit(:title, :content, images_attributes: [:src]).merge(user_id: current_user.id) 46: byebug => 47: end 48: 49: def set_post 50: @post = Post.find(params[:id]) 51: end (byebug) params <ActionController::Parameters {"utf8"=>"✓", "authenticity_token"=>"avP5DeA8ZSPhaUMkOvPmvW1rF7ML5bptV+cb6PMs3O5pcsBXzvHZtTVzWo0iWPC5crB/actaEN/AquKCzZY9ZA==", "post"=><ActionController::Parameters {"images_attributes"=>{"0"=>{"src"=>#<ActionDispatch::Http::UploadedFile:0x00007ff3b20f7438 @tempfile=#<Tempfile:/var/folders/ww/kfxy7w0565x8jj51gtp67gmr0000gn/T/RackMultipart20200312-43216-1o11cr3.png>, @original_filename="スクリーンショット 2020-03-04 16.04.20.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"post[images_attributes][0][src]\"; filename=\"\xE3\x82\xB9\xE3\x82\xAF\xE3\x83\xAA\xE3\x83\xBC\xE3\x83\xB3\xE3\x82\xB7\xE3\x83\xA7\xE3\x83\x83\xE3\x83\x88 2020-03-04 16.04.20.png\"\r\nContent-Type: image/png\r\n">}}, "title"=>"1234", "content"=>"5677"} permitted: false>, "commit"=>"Save", "controller"=>"posts", "action"=>"create"} permitted: false>

paramsまではデータが運ばれていると思いました。

#現状の疑わしい点の整理

①paramsの値が返ってこないcreateアクションが怪しい・・・

 ・createアクションがimageのデータを読み込まれてない?

②アソシエーションの問題かも??
・postしたときに画像も保存するようになってるだろうか?

#【調べたこと・試したこと】
細かいところをいじったり、参考にしたりと、かなり色々試したのですが、
以下が怪しいと思いましたので記載します。

byebugで値がとれているのか否か?? を調べました。

①createアクションは反応ないので(ここが怪しい・・・・と思いました)

controller

1 2def create 3 @post = Post.new(post_params) 4 byebug 5 ↑上記反応なし 6 if @post.save 7 redirect_to root_path, notice: "投稿しました" 8 else 9 flash[:alert] = "入力してください" 10 render :new 11 end 12 end

paramsでbyebugしてみると

controller

1 2def post_params 3 params.require(:post).permit(:title, :content, images_attributes: [:src]).merge(user_id: current_user.id) 4 byebug 5 end

↑この記述では、paramsの値が返ってきました(上記paramsのメッセージについてに記載済み)

#各ファイルのデータについて

①モデル

user.rb

user

1class User < ApplicationRecord 2 3 devise :database_authenticatable, :registerable, 4 :recoverable, :rememberable, :validatable 5 6 has_many :posts 7end

post.rb

post

1 2class Post < ApplicationRecord 3 4 has_many :images 5 belongs_to :user 6 7 accepts_nested_attributes_for :images 8end

image.rb

image

1 2class Image < ApplicationRecord 3 mount_uploader :src, ImageUploader 4 belongs_to :posts 5end

image_uploader.rb

class ImageUploader < CarrierWave::Uploader::Base # Include RMagick or MiniMagick support: # include CarrierWave::RMagick include CarrierWave::MiniMagick # Choose what kind of storage to use for this uploader: storage :file # storage :fog # Override the directory where uploaded files will be stored. # This is a sensible default for uploaders that are meant to be mounted: def store_dir "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end # Provide a default URL as a default if there hasn't been a file uploaded: # def default_url(*args) # # For Rails 3.1+ asset pipeline compatibility: # # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_')) # # "/images/fallback/" + [version_name, "default.png"].compact.join('_') # end # Process files as they are uploaded: # process scale: [200, 300] # # def scale(width, height) # # do something # end # Create different versions of your uploaded files: # version :thumb do # process resize_to_fit: [50, 50] # end # Add a white list of extensions which are allowed to be uploaded. # For images you might use something like this: # def extension_whitelist # %w(jpg jpeg gif png) # end # Override the filename of the uploaded files: # Avoid using model.id or version_name here, see uploader/store.rb for details. # def filename # "something.jpg" if original_filename # end process resize_to_fit: [100, 100] end

②view
_post.html.erb

<%# コメント&画像投稿エリア %> <div class="album py-5 bg-light"> <div class="container"> <div class="row"> <% @posts.each do |post| %> <div class="col-md-4"> <div class="card mb-4 shadow-sm"> <!-- 画像投稿フォーム ここから --> <% post.images.each do |image| %> <%= image_tag image.src.url %> <% end %> <!-- 画像投稿フォーム ここまで --> <div class="card-body"> <p class="card-text"><%= post.content %></p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group justify-content-center"> <button type="button" class="btn btn-sm btn-outline-secondary"><%= post.title %></button> <div class="field"> <%= post.user.nickname %><br>様の投稿 </div> <button type="button" class="btn btn-sm btn-outline-secondary">いいね♡</button> </div> </div> <small class="text-muted"><%= l post.created_at %></small> <button type="button" class="btn btn-sm"><%= post.id %>回目の投稿</button> <% if user_signed_in? %> <%= link_to "編集", edit_post_path(post), class: 'btn btn-primary my-2' %> <% else %> <%= "" %> <% end %> </div> </div> </div> <% end %> </div> </div> </div>

new.html.erb

<div> <div class = "col-md-4 offset-md-4"> <h2 class = "text-center">new post</h2> <%= render partial: "form" %> </div> <div class = "col-md-4 offset-4"> <%= link_to 'トップ', root_path %> </div> </div>

index.html.erb

<%= render partial: "devise/shared/header" %> <%# 会員登録、ログイン%> <main role="main"> <section class="jumbotron text-center"> <div class="container"> <h3>ワンペタノート</h3> <p class="lead text-muted">画像も投稿できる掲示板です</p> <p> <% if user_signed_in? %> <%= link_to "新規投稿", new_post_path, class: 'btn btn-primary my-2' %> <%= link_to "ログアウト", destroy_user_session_path, method: :delete, class: 'btn btn-primary my-2' %> <% else %> <%= link_to "新規登録", new_user_registration_path, class: 'btn btn-primary my-2' %> <%= link_to "ログイン", new_user_session_path, class: 'btn btn-primary my-2' %> <% end %> </p> </div> </section> <%= render partial: 'post', collection: @posts %> <%= render :partial => "devise/shared/footer" %>

③コントローラー
post_controller.rb

controller

1 2class PostsController < ApplicationController 3 4 before_action :set_post, except: [:index, :new, :create] 5 6 def index 7 @posts = Post.includes(:user, :images).all.order('created_at DESC') 8 end 9 10 def show 11 @post = Post.find(params[:id]) 12 end 13 14 def new 15 @post = Post.new 16 @post.images.new 17 end 18 19 def create 20 @post = Post.new(post_params) 21 if @post.save 22 redirect_to root_path, notice: "投稿しました" 23 else 24 flash[:alert] = "入力してください" 25 render :new 26 end 27 end 28 29 def edit 30 @post = Post.find(params[:id]) 31 end 32 33 def update 34 @post = Post.find(params[:id]) 35 if @post.update(post_params) 36 redirect_to root_path, notice: "success" 37 else 38 flash[:alert] = "save error" 39 render :edit 40 end 41 end 42 43 private 44 45 def post_params 46 params.require(:post).permit(:title, :content, images_attributes: [:src]).merge(user_id: current_user.id) 47 end 48 49 def set_post 50 @post = Post.find(params[:id]) 51 end 52end

#ER図は以下のように考えてます。

余計な情報かもしれませんが・・・おかしな点がございましたらご指摘いただけますと幸いです。
イメージ説明

#参考にさせていただいた記事
carrierwaveを利用して画像をアップロードしたがDBに保存されない
Rails4 で form_for が multipart にならない

【メモ】Strong Parametersの概要と配列データの扱い方について
paramsを用いた投稿画面の作成と保存

[学習用]Rails5:CarrierWaveで画像投稿+rmagickでサムネイル保存+画像名ランダム化

以上となります。
長くなってしまい申し訳ございません。

最後までみていただき、ありがとうございます。

s.k👍を押しています

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

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

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

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

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

guest

回答1

0

自己解決

解決できました。
やはり単純な問題でした・・・

ruby

1belongs_to :posts

ruby

1belongs_to :post

に変更

単数形にしました。

belongs_to :postsで、saveしたあとに、リダイレクトと記述していたのに、
なぜ画像が保存されていないのに、リダイレクトされてしまっていたのかは不明ですが、

post.imagesの値がきていないことによってアソシエーションエラーが発生しているのに気づけました。

投稿2020/03/17 09:37

pontarou3

総合スコア18

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問