解決したいこと
インスタライクなアプリを制作しており、マイページにログインユーザーのみの投稿を表示されたいのですが、全てのユーザーの投稿が表示されてしまう。
users_controller.rb
ruby
1class UsersController < ApplicationController 2 3 def show 4 user = User.find(params[:id]) 5 @nickname = user.nickname 6 @posts = user.posts 7 @posts = Post.includes(:user).order("created_at DESC").page(params[:page]).per(5) 8 end 9end
posts_controller.rb
ruby
1class PostsController < ApplicationController 2 before_action :set_post, only: [:edit, :show] 3 before_action :move_to_index, except: [:index, :show] 4 5 def index 6 @posts = Post.includes(:user).order("created_at DESC").page(params[:page]).per(5) 7 end 8 9 def new 10 @post = Post.new 11 end 12 13 def create 14 @post = Post.new(post_params) 15 if @post.save! 16 redirect_to root_path 17 else 18 render :new 19 end 20 end 21 22 def destroy 23 post = Post.find(params[:id]) 24 post.destroy 25 end 26 27 def edit 28 end 29 30 def update 31 post = Post.find(params[:id]) 32 post.update(post_params) 33 end 34 35 def show 36 end 37 38 private 39 def post_params 40 params.require(:post).permit(:tag_id, :title, :text, :image).merge(user_id: current_user.id) 41 end 42 43 def set_post 44 @post = Post.find(params[:id]) 45 end 46 47 def move_to_index 48 redirect_to action: :index unless user_signed_in? 49 end 50end
application_controller.rb
ruby
1class ApplicationController < ActionController::Base 2 3 protect_from_forgery with: :exception 4 before_action :configure_permitted_parameters, if: :devise_controller? 5 6 protected 7 def configure_permitted_parameters 8 added_attrs = [ :image, :nickname, :email, :password, :password_confirmation ] 9 devise_parameter_sanitizer.permit :sign_up, keys: added_attrs 10 devise_parameter_sanitizer.permit :sign_in, keys: added_attrs 11 devise_parameter_sanitizer.permit :account_update, keys: added_attrs 12 end 13 14end
models/user.rb
ruby
1class User < ApplicationRecord 2 devise :database_authenticatable, :registerable, 3 :recoverable, :rememberable, :validatable 4 has_many :posts, dependent: :destroy 5 6 mount_uploader :image, ImageUploader 7end
models/post.rb
ruby
1class Post < ApplicationRecord 2 validates :tag_id, :title, :text, :image, presence: true 3 belongs_to :user 4 belongs_to :tag 5 6 mount_uploader :image, ImageUploader 7end
routes.rb
ruby
1Rails.application.routes.draw do 2 devise_for :users 3 root to: 'posts#index' 4 resources :posts 5 resources :users, only: :show 6end
showアクションbinding.pry後のパラメーター
terminal
1=> <ActionController::Parameters {"controller"=>"users", "action"=>"show", "id"=>"1"} permitted: false>
ご助力よろしくお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/05/18 07:50
2020/05/19 00:12