我只想在我的rails应用程序中显示用户在索引页面中创建的帖子而不是所有帖子

时间:2017-07-10 07:25:49

标签: ruby-on-rails ruby model-view-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

我的模特:

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

现在我要做的就是在我的索引操作中,所有帖子我只需要创建它的用户的帖子,所以当用户登录时 应该重定向到他自己的帖子而不是所有帖子。我是铁杆新手,任何建议都将不胜感激。我不知道要在索引中添加什么以及在视图中添加什么。我用过Devise

2 个答案:

答案 0 :(得分:2)

这样就可以了:

def index
  @post = current_user.posts
end

答案 1 :(得分:0)

只需更改控制器的索引方法即可。

def index
  @posts = Post.where(:user_id => current_user.id)
end

这将为您提供属于登录用户的一系列帖子。还有一件事,请重命名索引中的对象&#39; post&#39;到帖子&#39;因为结果不是一个帖子。