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

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

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

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

Q&A

解決済

1回答

654閲覧

userモデルにpostモデルの紐ずけ

shuri

総合スコア5

Ruby on Rails

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

0グッド

0クリップ

投稿2020/01/26 15:44

前提・実現したいこと

ここに質問の内容を詳しく書いてください。
簡単なツイッターみたいなのを作っています
■な機能を実装中に以下のエラーメッセージが発生しました。
userのshowページに自分が投稿したもの(post)を持って来るときにエラーが出ました。

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

NoMethodError in Public::Users#show
Showing /vagrant/portfolio3/app/views/public/users/show.html.erb where line #15 raised:

undefined method `posts' for nil:NilClass

エラーメッセージ

該当のソースコード

モデル
class User < ApplicationRecord

Include default devise modules. Others available are:

:confirmable, :lockable, :timeoutable, :trackable and :omniauthable

devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable

has_many :nices, dependent: :destroy
has_many :posts, dependent: :destroy
has_many :comments, dependent: :destroy
has_many :dms, dependent: :destroy
has_many :relationships, dependent: :destroy
has_many :entries, dependent: :destroy

has_many :following_relationships, foreign_key: "follower_id", class_name: "Relationship", dependent: :destroy

has_many :followings, through: :following_relationships

has_many :follower_relationships, foreign_key: "following_id", class_name: "Relationship", dependent: :destroy

has_many :followers, through: :follower_relationships

def following?(other_user)
following_relationships.find_by(following_id: other_user.id)
end

def follow!(other_user
following_relationships.create!(following_id: other_user.id)
end

def unfollow!(other_user)
following_relationships.find_by(following_id: other_user.id).destroy
end

def already_niced?(post)
self.nices.exists?(post_id: post.id)
end

end

ポストモデル
class Post < ApplicationRecord
belongs_to :user
has_many :nices, dependent: :destroy
has_many :iine_users, through: :likes, source: :user
has_many :comments, dependent: :destroy

def niced_by?(user)
nices.where(user_id: user.id).exists?
end

def nice_user(user_id)
nices.find_by(user_id: user_id)
end

def uniine(user)
nices.find_by(user_id: user.id).destroy
end
end

コントローラー
class Public::PostsController < Public::ApplicationController
before_action :authenticate_user!

def index
@posts = Post.all
end

def new
@post = Post.new
end

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

def show
@post = Post.find(params[:id])
@post_new = Post.new
@nice = Nice.new
@commentnew = Comment.new
end

def update
@post = Post.find(params[:id])
@post.update(post_params)
redirect_to public_post_path(@post.id), flash:{success: "You have updated user successfully."}
end

def create
@post = Post.new(post_params)
@post.user_id = current_user.id
if @post.save
redirect_to public_post_path(@post.id)
else
@posts = Post.all
render :new
end
end

def destroy
end

private

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

userコントローラー
class Public::UsersController < Public::ApplicationController
before_action :authenticate_user!, :only => [:show]

def edit
@user = User.find(params[:id])
end

def update
@user = User.find(params[:id])
if@user.update(user_params)
redirect_to public_user_path(@user.id), flash:{success: "You have updated user successfully."}
else
render action: :edit
end
end

def index
@user =User.all
@q = User.ransack(params[:q])
@users = @q.result
end

end

def show
@users = current_user
@user = User.find(params[:id])
@currentUserEntry=Entry.where(user_id: current_user.id)
@userEntry=Entry.where(user_id: @user.id)
if @user.id == current_user.id
else
@currentUserEntry.each do |cu|
@userEntry.each do |u|
if cu.room_id == u.room_id then
@isRoom = true
@roomId = cu.room_id
end
end
end
if @isRoom
else
@room = Room.new
@entry = Entry.new
end
end
end

def out
end

def destroy
end

def search
end

def following
@user = User.find(params[:id])
@users = @user.followings
render 'show_follow'
end

def followers
@user = User.find(params[:id])
@users = @user.followers
render 'show_follower'
end

private

def user_params
params.require(:user).permit(:nickname, :phone, :email, :profile_image)
end

def user_find
@user = User.find(params[:id])
end

スキーマーshema post

create_table "posts", force: :cascade do |t|
t.string "title", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "body"
t.integer "nices_count", default: 0, null: false
t.integer "user_id"
end

問題のビュー ユーザーショウページ

<section class="sct-color-1 slice"> <div class="container-fluid masonry-container"> <div class="row"> <div class="col-md-8 col-sm-offset-2"> <div class="masonry-wrapper-cols"> <div class="masonry-gutter"></div> <div class="masonry-block"> <div class="block block-image v1"> <div class="block-image"> <div class="view view-first"> </div> </div> <div class="block-content"> <h3 class="block-title"> <% @user.posts.each do |toukou| %> <%= toukou.title %> <%= toukou.body %> <%= link_to "詳細", public_post_path(toukou) %> <%= link_to "編集", edit_public_post_path(toukou) %> <% end %> </h3> <ul class="inline-meta"> <li> </li> <li> </li> </ul>
</div> </div> </div> </div> </div> </div>
</div> </section>
rails

試したこと

モデルやコントローラーの見直しなどいろいろ

ここに問題に対して試したことを記載してください。

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

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

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

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

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

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

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

guest

回答1

0

ベストアンサー

<% @user.posts.each do |toukou| %>
エラーの原因はビューファイルのこの部分だと思います。

一例ですが、ユーザー自身が投稿したものを見せたいのであれば、userのコントローラのshowアクションに

ruby

1def show 2 @user = User.find(params[:id]) 3 @posts = @user.posts.order('created_at DESC')

と定義して、ビューには

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

と書くのが良いと思います。

あと、質問のコードがかなり読みにくいので、ちゃんとコードの部分に貼り付けしてくれた方が多くの方がちゃんとレビューしてくれると思います。

投稿2020/01/26 16:03

bamboo-nova

総合スコア1408

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

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

shuri

2020/01/29 06:22

回答ありがとうございます! 解答者様のおかげで無事に解決することができました! 質問の仕方についてのご指摘までありがとうございます! 次からはもうちょっと見やすいように質問させていただきます!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問