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

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

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

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

Ruby on Rails

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

Q&A

解決済

1回答

361閲覧

Railsで掲示板投稿機能での画像表示ができない

ocs_R

総合スコア6

Ruby

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

Ruby on Rails

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

1グッド

0クリップ

投稿2020/11/24 02:03

編集2020/11/25 05:35

Rails初心者です。
post.user.image_nameの方は表示されるのですが、
post.post.post_imageはメソッドエラーが出てしまい表示できません。
どこがおかしいのでしょうか?

イメージ説明

index.html.erb

rails

1<div class="main posts-index"> 2 <div class="container"> 3 <% @posts.each do |post| %> 4 <div class="posts-index-item"> 5 <div class="post-left"> 6 <!-- ユーザーの画像が表示されるように、以下のsrcに値を追加してください --> 7 8 <img src="<%= "/#{post.user.image_name}" %>"> 9 </div> 10 <div class="post-right"> 11 <img src="<%= "/post_images/#{post.post.post_image}" %>"> 12 13 14 <div class="post-user-name"> 15 16 <!-- link_toメソッドを用いて、ユーザー詳細ページへのリンクを作成してください --> 17 18 </div> 19 <%= link_to(post.content, "/posts/#{post.id}") %> 20 21 </div> 22 23 </div> 24 25 <% end %> 26 </div> 27 28</div> 29

posts_controller.rb

rails

1class PostsController < ApplicationController 2 before_action :authenticate_user 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 # 変数@likes_countを定義してください 13 @likes_count = Like.where(post_id: @post.id).count 14 end 15 16 def new 17 @post = Post.new 18 end 19 20 def create 21 @post = Post.new( 22 content: params[:content], 23 user_id: @current_user.id) 24 #,post_image: nil) 25 @post.save 26 27 if @post.save 28 29 if params[:post_image] 30 @post.post_image = "#{@post.id}.jpg" 31 image = params[:post_image] 32 File.binwrite("public/post_images/#{@post.post_image}",image.read) 33 end 34 35 flash[:notice] = "投稿を作成しました" 36 redirect_to("/posts/index") 37 else 38 render("posts/new") 39 end 40 end 41 42 43 def edit 44 @post = Post.find_by(id: params[:id]) 45 end 46 47 def update 48 @post = Post.find_by(id: params[:id]) 49 @post.content = params[:content] 50 if @post.save 51 flash[:notice] = "投稿を編集しました" 52 redirect_to("/posts/index") 53 else 54 render("posts/edit") 55 end 56 end 57 58 def destroy 59 @post = Post.find_by(id: params[:id]) 60 @post.destroy 61 flash[:notice] = "投稿を削除しました" 62 redirect_to("/posts/index") 63 end 64 65 def ensure_correct_user 66 @post = Post.find_by(id: params[:id]) 67 if @post.user_id != @current_user.id 68 flash[:notice] = "権限がありません" 69 redirect_to("/posts/index") 70 end

users_controller.rb

rails

1class UsersController < ApplicationController 2 before_action :authenticate_user, {only: [:index, :show, :edit, :update]} 3 before_action :forbid_login_user, {only: [:new, :create, :login_form, :login]} 4 before_action :ensure_correct_user, {only: [:edit, :update]} 5 6 def index 7 @users = User.all 8 end 9 10 def show 11 @user = User.find_by(id: params[:id]) 12 end 13 14 def new 15 @user = User.new 16 end 17 18 def create 19 @user = User.new( 20 name: params[:name], 21 email: params[:email], 22 image_name: "054.jpg", 23 password: params[:password] 24 ) 25 if @user.save 26 session[:user_id] = @user.id 27 flash[:notice] = "ユーザー登録が完了しました" 28 redirect_to("/users/#{@user.id}") 29 else 30 render("users/new") 31 end 32 end 33 34 def edit 35 @user = User.find_by(id: params[:id]) 36 end 37 38 def update 39 @user = User.find_by(id: params[:id]) 40 @user.name = params[:name] 41 @user.email = params[:email] 42 43 if params[:image] 44 @user.image_name = "#{@user.id}.jpg" 45 image = params[:image] 46 File.binwrite("public/#{@user.image_name}", image.read) 47 end 48 49 if @user.save 50 flash[:notice] = "ユーザー情報を編集しました" 51 redirect_to("/users/#{@user.id}") 52 else 53 render("users/edit") 54 end 55 end 56 57 def login_form 58 end 59 60 def login 61 @user = User.find_by(email: params[:email], password: params[:password]) 62 if @user 63 session[:user_id] = @user.id 64 flash[:notice] = "ログインしました" 65 redirect_to("/posts/index") 66 else 67 @error_message = "メールアドレスまたはパスワードが間違っています" 68 @email = params[:email] 69 @password = params[:password] 70 render("users/login_form") 71 end 72 end 73 74 def logout 75 session[:user_id] = nil 76 flash[:notice] = "ログアウトしました" 77 redirect_to("/login") 78 end 79 80 def likes 81 # 変数@userを定義してください 82 @user = User.find_by(id: params[:id]) 83 84 # 変数@likesを定義してください 85 @likes = Like.where(user_id: @user.id) 86 end 87 88 def ensure_correct_user 89 if @current_user.id != params[:id].to_i 90 flash[:notice] = "権限がありません" 91 redirect_to("/posts/index") 92 end

application_record.rb

rails

1class ApplicationRecord < ActiveRecord::Base 2 self.abstract_class = true 3end 4

like.rb

rails

1class Like < ApplicationRecord 2 validates :user_id, {presence: true} 3 validates :post_id, {presence: true} 4 end 5

post.rb

rails

1class Post < ApplicationRecord 2 validates :content, {presence: true, length: {maximum: 140}} 3 validates :user_id, {presence: true} 4 5 # インスタンスメソッドuserを定義してください 6 def user 7 return User.find_by(id: self.user_id) 8 end 9 10end 11

user.rb

rails

1class User < ApplicationRecord 2 validates :name, {presence: true} 3 validates :email, {presence: true, uniqueness: true} 4 validates :password, {presence: true} 5 6 # インスタンスメソッドpostsを定義してください 7 def posts 8 return Post.where(user_id: self.id) 9 end 10 11end 12

schema.rb

rails

1# This file is auto-generated from the current state of the database. Instead 2# of editing this file, please use the migrations feature of Active Record to 3# incrementally modify your database, and then regenerate this schema definition. 4# 5# Note that this schema.rb definition is the authoritative source for your 6# database schema. If you need to create the application database on another 7# system, you should be using db:schema:load, not running all the migrations 8# from scratch. The latter is a flawed and unsustainable approach (the more migrations 9# you'll amass, the slower it'll run and the greater likelihood for issues). 10# 11# It's strongly recommended that you check this file into your version control system. 12 13ActiveRecord::Schema.define(version: 2020_10_30_055415) do 14 15 create_table "likes", force: :cascade do |t| 16 t.integer "user_id" 17 t.integer "post_id" 18 t.datetime "created_at", null: false 19 t.datetime "updated_at", null: false 20 end 21 22 create_table "posts", force: :cascade do |t| 23 t.text "content" 24 t.datetime "created_at", null: false 25 t.datetime "updated_at", null: false 26 t.integer "user_id" 27 t.string "post_image" 28 end 29 30 create_table "users", force: :cascade do |t| 31 t.string "name" 32 t.string "email" 33 t.datetime "created_at", null: false 34 t.datetime "updated_at", null: false 35 t.string "image_name" 36 t.string "password" 37 end 38 39end

追記

index.html.erbの中の
<img src="<%= "/post_images/#{post.post.post_image}" %>">を
<img src="<%= "/post_images/#{post.post_image}" %>">
に変更し、エラーは消えましたが画像がうまく表示できませんでした。
イメージ説明

イメージ説明

posts_controllerのif @post.saveを変更。
イメージ説明

punchan36👍を押しています

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

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

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

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

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

m.ts10806

2020/11/24 02:09

モデルのリレーションはどうなっているのでしょうか。
ocs_R

2020/11/24 02:17

こうなっております。 application_record.rb class ApplicationRecord < ActiveRecord::Base self.abstract_class = true end like.rb class Post < ApplicationRecord validates :content, {presence: true, length: {maximum: 140}} validates :user_id, {presence: true} # インスタンスメソッドuserを定義してください def user return User.find_by(id: self.user_id) end end post.rb class Post < ApplicationRecord validates :content, {presence: true, length: {maximum: 140}} validates :user_id, {presence: true} # インスタンスメソッドuserを定義してください def user return User.find_by(id: self.user_id) end end user.rb class User < ApplicationRecord validates :name, {presence: true} validates :email, {presence: true, uniqueness: true} validates :password, {presence: true} # インスタンスメソッドpostsを定義してください def posts return Post.where(user_id: self.id) end end
m.ts10806

2020/11/24 02:31

質問は編集できますし、こちらのコメント欄ではマークダウン使えませんので原則質問本文を更新してください
ocs_R

2020/11/24 02:36

追加いたしました、よろしくお願いします。
punchan36

2020/11/24 06:32

schema.rbを追記して頂けませんか?
ocs_R

2020/11/25 04:23

追加いたしました。よろしくお願いします。
guest

回答1

0

ベストアンサー

posts_controller.rbを拝見する限り、投稿用の画像のカラム名は恐らくpost_imageになっているかと思います。
posts/index.html.erbにある該当のコードを、下記の様に変えてみてはいかがでしょうか。

Rails

1 <img src="<%= "/post_images/#{post.post.post_image}" %>"> 2  ↓ 3 <img src="<%= "/post_images/#{post.post_image}" %>">

【追記】
posts_controller.rbif @post.save以下をこの様に変更してみてはいかかでしょうか。

Ruby

1 if @post.save 2 if params[:post_image] 3   @post.post_image = "#{@post.id}.jpg" 4   post_image = params[:post_image] 5   File.binwrite("public/post_images/#{@post.post_image}", post_image.read) 6 end 7 @post.save 8 flash[:notice] = "投稿を作成しました" 9 redirect_to("/posts/index") 10 else 11 render("posts/new") 12 end

投稿2020/11/24 12:42

編集2020/11/25 05:13
punchan36

総合スコア105

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

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

ocs_R

2020/11/25 04:49 編集

回答ありがとうございます。 コードを変更したのですが、画像表示がうまくできませんでした。 追記したので確認してもらってもよろしいでしょうか。 宜しくお願い致します。
punchan36

2020/11/25 04:57

コード変更後に再度新規で「画像選択+投稿」をしても、新しい投稿もスクリーンショットの様に上手く表示されませんでしょうか?
ocs_R

2020/11/25 05:00

はい、一応フォルダの方には保存されているのですが、画像表示はできませんでした。
punchan36

2020/11/25 05:14

posts_controller.rbに関して回答に追記しました。そちらの方法ではどうでしょうか。
ocs_R

2020/11/25 05:44 編集

コードを入力をしてみましたが、メソッドエラーがでました。
ocs_R

2020/11/25 06:02 編集

全角の空白のスペースがあったみたいなので、修正したら動きました。 ありがとうございました!!!!!!!!!!!!!!!!!!
punchan36

2020/11/25 06:22

良かったです! コードを拝見させて頂いた感じ、progateでrailsを勉強しながらご自身でも試行錯誤されている所でしょうか?私もそうです。以前似たような所で躓いた事がありましたので、こちらもご参考になればと思います。 https://teratail.com/questions/300186 お互い頑張りましょう!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問