[英]i only want to display posts created by user in index page in my rails app instead of all posts
This is my posts controller: 这是我的帖子控制器:
class PostsController < ApplicationController
before_action :authenticate_user!
def index
@post = Post.all
end
def new
@post = Post.new
end
def create
@post = Post.new(set_post)
@post.user_id = current_user.id
if @post.save
redirect_to post_path(@post)
else
redirect_to new_post_path
end
end
My models: 我的模特:
class Post < ActiveRecord::Base
has_attached_file :image, styles: { medium: "400x400#" }
validates_attachment_content_type :image, content_type: /\Aimage
\/.*\Z/
belongs_to :user
end
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :posts
end
Now what I have to do is in my index action where there are all posts I need only the post of user who created it, so when user gets logged in he should be redirected to his own posts instead of all posts. 现在我需要做的是在索引操作中,其中所有帖子我只需要创建它的用户的帖子,因此,当用户登录时,应该将他重定向到他自己的帖子,而不是所有帖子。 I am new to rails, any suggestion would be appreciated. 我是Rails的新手,任何建议将不胜感激。 I don't know what to put in index and what to add in views. 我不知道该在索引中添加什么,以及在视图中添加什么。 I have used Devise 我用过Devise
This would do that: 这样可以做到:
def index
@post = current_user.posts
end
Just change your controller's index method. 只需更改控制器的索引方法即可。
def index
@posts = Post.where(:user_id => current_user.id)
end
This will give you an array of posts belonging to the user logged in. And one more thing, please rename the object in index from 'post' to 'posts' since the result is not a single post. 这将为您提供一系列属于已登录用户的帖子。还有一件事,请将索引中的对象从“ post”重命名为“ posts”,因为结果不是单个帖子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.