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

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

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

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails

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

HTML

HTMLとは、ウェブ上の文書を記述・作成するためのマークアップ言語のことです。文章の中に記述することで、文書の論理構造などを設定することができます。ハイパーリンクを設定できるハイパーテキストであり、画像・リスト・表などのデータファイルをリンクする情報に結びつけて情報を整理します。現在あるネットワーク上のほとんどのウェブページはHTMLで作成されています。

CSS

CSSはXMLやHTMLで表現した色・レイアウト・フォントなどの要素を指示する仕様の1つです。

Q&A

解決済

1回答

1902閲覧

railsでアップロードした画像ファイルがindexでうまく表示されません

1234567

総合スコア7

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails

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

HTML

HTMLとは、ウェブ上の文書を記述・作成するためのマークアップ言語のことです。文章の中に記述することで、文書の論理構造などを設定することができます。ハイパーリンクを設定できるハイパーテキストであり、画像・リスト・表などのデータファイルをリンクする情報に結びつけて情報を整理します。現在あるネットワーク上のほとんどのウェブページはHTMLで作成されています。

CSS

CSSはXMLやHTMLで表現した色・レイアウト・フォントなどの要素を指示する仕様の1つです。

0グッド

0クリップ

投稿2020/01/01 09:53

編集2020/01/02 05:24

前提・実現したいこと

Ruby on Railsにてポートフォリオの作成中です。投稿一覧ページにてTwitterや食べログのような投稿したテキスト+画像ファイルの表示をindexにて行いたい

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

イメージ説明
このように投稿した画像が文字化け?の様になってしまい、投稿一覧ページで画像が表示できなくて困っています。

エラーメッセージ

該当のソースコード

「posts/index.html.erb」

<div class="posts-wrapper"> <div class="posts-container">

<% @posts.each do |post| %>

<div class="posts-index-item"> <div class="post-user-name"> <div class="posts"> <div class="post-img"> <%= image_tag "/@post.image_name", alt: nil, id: "public", class: "image" %><br> </div> <%= link_to(post.content, "/posts/#{post.id}") %><br>  </div> </div> </div> <% end %>

該当のソースコード

[posts_controller.rb]
class PostsController < ApplicationController
before_action :authenticate_user
before_action :ensure_correct_user, {only: [:edit, :update, :destroy]}

def index
@posts = Post.page(params[:page]).per(5).order(created_at: :desc)
@post = Post.find_by(id: params[:id])
if params[:image]
@post.image_name = "#{@post.id}.jpg"
image = params[:image]
File.binwrite("public/images_folder/#{@post.image_name}", image.read )
else

end

end

def show
@post = Post.find_by(id: params[:id])
@user = User.find_by(id: @post.user_id)

if params[:image] @post.image_name = "#{@post.id}.jpg" image = params[:image] File.binwrite("public/post_images/#{@post.image_name}", image.read) end

end

def new
@post = Post.new
if @current_user == nil
flash[:notice] = "ログインして下さい"
redirect_to("/login")
end
end

def create
@post = Post.new(
content: params[:content],
image_name: params[:image],
user_id: @current_user.id
)

if params[:image]
@post.image_name = "#{@post.id}.jpg"
image = params[:image]
File.binwrite("public/images_folder/#{@post.image_name}", image.read)
end

if @post.save
redirect_to("/posts/index")
flash[:notice] = "投稿しました"
else
render("/posts/new")
end
end

def edit
@post = Post.find_by(id: params[:id])
end

def update
@post = Post.find_by(id: params[:id])
@post.content = params[:content]

if params[:image]
@post.image_name = "#{@post.id}.jpg"
image = params[:image]
File.binwrite("public/post_images/#{@post.image_name}", image:read)
end

if @post.save
redirect_to("/posts/index")
flash[:notice] = "投稿の編集をしました"
else
redirect_to("/posts/#{@post.id}/edit")
end
end

def destroy
@post = Post.find_by(id: params[:id])
@post.destroy
redirect_to("/posts/index")
flash[:notice] = "削除しました"
end

def ensure_correct_user
@post = Post.find_by(id: params[:id])
if @post.user_id != @current_user.id
flash[:notice] = "ユーザーが一致しません"
redirect_to("/posts/index")
end
end

private

def post_params
params.require(:post).permit(:title, :image)
end

end

該当のソースコード

[upload.rb]

class Upload < ApplicationRecord
mount_uploader :image, ImageUploader
end

該当のソースコード

[post.rb]
class Post < ApplicationRecord
mount_uploader :image, ImageUploader
end

該当のソースコード

[Gemfile]
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.6.3'

gem 'rails-i18n'

Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '> 6.0.1'
Use sqlite3 as the database for Active Record
gem 'sqlite3', '
> 1.4'
Use Puma as the app server
gem 'puma', '> 4.1'
Use SCSS for stylesheets
gem 'sass-rails', '>= 6'
Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
gem 'webpacker', '
> 4.0'
Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '> 5'
Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '
> 2.7'
Use Redis adapter to run Action Cable in production
gem 'redis', '> 4.0'
Use Active Model has_secure_password
gem 'bcrypt', '
> 3.1.7'
Use Active Storage variant
gem 'image_processing', '~> 1.2'

Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.4.2', require: false

group :development, :test do
Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end

group :development do
Access an interactive console on exception pages or by calling 'console' anywhere in the code.
gem 'web-console', '>= 3.3.0'
gem 'listen', '>= 3.0.5', '< 3.2'
Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
end

group :test do
Adds support for Capybara system testing and selenium driver
gem 'capybara', '>= 2.15'
gem 'selenium-webdriver'
Easy installation and use of web drivers to run system tests with browsers
gem 'webdrivers'
end

Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

gem "refile", github: 'refile/refile', require: "refile/rails"
gem "refile-mini_magick", github: 'refile/refile-mini_magick'

gem 'kaminari'

gem 'carrierwave', '~> 2.0.2'
gem 'mini_magick'

該当のソースコード

[posts/new.html.erb]

<div class="main-posts-new"> <div class="container"> <h1 class="form-heading">本を要約してメモする</h1><br> <h4>本のタイトル・作者</h4> <%= form_tag("/posts/create", {multipart: true}) do %> <div class="form"> <div class="form-body"> <% @post.errors.full_messages.each do |message| %> <div class="form-error"> <%= message %> </div> <% end %> <textarea name="content"><%= @post.content %></textarea> <h4>画像</h4> <input name="image" type="file"> <h4>要約スペース</h4> <textarea name="content"><%= @post.content %></textarea><br> <input type="submit" value="投稿"> </div> </div> <% end %> </div> </div>
Ruby on Rails

試したこと

carrierwaveを使って試しましたが、変わらず。また画像ファイルの大きさも関係があるのかと思い、念のためCSSでスペースを多くとってみたりもしました。初心者のためうまく説明ができず申し訳ありません。何かわかることがあったら教えていただけると幸いです。。。

補足情報(FW/ツールのバージョンなど)

ここにより詳細な情報を記載してください。

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

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

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

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

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

退会済みユーザー

退会済みユーザー

2020/01/01 10:09 編集

viewだけのせても原因がわかりません。コントローラーとモデルのコードがないとcarrierwaveを正しくよべてるかわかりませんし、uploader クラスもないと設定が正しいかどうかもわかりません。view 以外みせられない(さわれない)のであれば<%= image_tag の直前に <% puts @post.image_name %> をはさんで値が保存されてるか確認してみてください。
1234567

2020/01/01 12:16

ご指摘ありがとうございます。コードの記載を追加いたしました。お時間ある時に目を通していただけたら幸いです。
退会済みユーザー

退会済みユーザー

2020/01/01 13:09 編集

今言えるのは `@post.image_name = "#{@post.id}.jpg"` でファイル名をセットしてて `File.binwrite("public/post_images/#{@post.image_name}", image:read)` と書き込み先は post_images なのに view では image_tag "/@post.image_name" とルート直下のパスになってるところです。エスケープされてないのとディレクトリもおかしいです。 image_tag で /public/post_images/#{@post.image_name} を指定する必要があります。アップがうまくいってるならこれだけで治ると思いますが、アップロードもうまくいってないなら new の view をみないとわかりません。
1234567

2020/01/02 05:37

<%= image_tag "/public/post_images/#{@post.image_name} %>と入力しましたが、エラーになってしまいました。(views/posts/new.html.erbも質問内に追加で記載しました) 色々と試してみたのですがアップロードの方にも原因がある様な気がしました。一度アップロードすると、投稿詳細ページで表示される画像全てが変更されて同じ画像が表示されてしまうという事象が起こっています。また、投稿内容の詳細ページでは画像は表示されています。 そして、色々と試してるうち余計なことをしてしまったのか、以前はそんなことなかったのですが投稿自体のアップロードもエラーが出る様になってしまいました。。ひとまず現時点では投稿一覧ページでの画像表示が出来ないことを解決したいと考えていますが、アップロード機能自体の見直しが結果的に原因なのでしょうか? 質問が悪かったら申し訳ありません。ご教授いただけると幸いです。
退会済みユーザー

退会済みユーザー

2020/01/02 09:12 編集

> エラーになって まずはりつけたままのコードを追加したなら image_tag の最期に " がいります。 `<%= image_tag("/public/post_images/#{@post.image_name}") %>` > 余計なこと carrierwave と混在しちゃってる気がしますね。carrierwave を使うなら ``` @post.image_name = "#{@post.id}.jpg" image = params[:image] File.binwrite("public/post_images/#{@post.image_name}", image.read) ``` この辺は自動でやってくれるので必要ないはずです。使わない(手動で保存する)なら carrierwave で追加したコードは全部削除したほうがいいです
退会済みユーザー

退会済みユーザー

2020/01/02 15:49

おなじになるで気づいたんですが追加したこの部分 @ つけちゃだめですね ループ変数の @ なし post にしないと全部同じなっちゃいます <%= image_tag("/public/post_images/#{post.image_name}") %>
1234567

2020/01/06 03:51 編集

carrierwaveに関するコードを一通り消したところアップロードは正常に戻りました!ありがとうございます。 ただ、 <% @posts.each do |post| %> <%= image_tag("/public/post_images/#{post.image_name}") %> <%= link_to(post.content, "/posts/#{post.id}") %> <% end %> の形にしてもやはり新しく投稿した画像に引っ張られて過去の画像も変わってしまいます。また投稿一覧ページの画像表示も変わらず文字化けのままです。 each文の@postsの@を消したりも試したのですが、変わらずでした。
shinoharat

2020/01/08 02:10 編集

> 新しく投稿した画像に引っ張られて過去の画像も変わってしまいます。 posts_controller.rb の create に問題がある気がします。 保存する前は id が決まっていない(nilになっている)ので、どんなファイルを保存しても `nil.jpg` という名前になっているはずです。 --------------------- def create  ・・・  if params[:image]   @post.image_name = "#{@post.id}.jpg" # ←この時点で id は常に nil   image = params[:image]   File.binwrite("public/images_folder/#{@post.image_name}", image.read)  end  if @post.save # ←この時点で id が決まる   ・・・ end ---------------------
shinoharat

2020/01/08 02:13

また、chica 様のおっしゃっている通り、画像の保存は carrierwave が勝手にやってくれるので、自前で実装しなくて良いです。 > carrierwaveに関するコードを一通り消したところアップロードは正常に戻りました! とのことですが、 (1) carrierwave を使うから自前の実装を消した (2) 自前で実装して carrierwave を消した のどちらなのか分からず、回答しづらいです。 現在の最新のコードを記載していただけると、他の方も回答しやすいと思います。
nasuk47

2020/01/09 10:10

<%= image_tag(post.画像のDBのカラム名.url) %> とかどうでしょうか?
guest

回答1

0

ベストアンサー

<%= image_tag "/@post.image_name", alt: nil, id: "public", class: "image" %><br>

とありますが、 "/@post.image_name"@post.image_name に変更してみてください。

@post.image_name であれば変数で展開されますが、
"" で囲むと展開されません。そのまま文字列になってしまいます。

結果として、ご提示のコードは、"/@post.image_name" というファイル名の画像を出すコードになってしまい、そのようなファイル名の画像はないので、画像が出ないということになっていそうです。

投稿2020/01/10 19:14

退会済みユーザー

退会済みユーザー

総合スコア0

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問