【问题标题】:Displaying posts by specific user?显示特定用户的帖子?
【发布时间】:2013-01-26 03:32:57
【问题描述】:

这里有一些代码:

def show
    @post = Post.find()
  end
end

用户模型有has_many :posts 并且帖子模型有belongs_to :user。现在如何使显示操作仅显示登录用户的帖子。登录用户是“current_user”?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 devise


    【解决方案1】:

    你可以这样做:

    def show
      @post = Post.where(user_id: current_user.id)
    end
    

    但是变量存在故障,您应该将@post 重命名为@posts,因为这将是一个包含多个帖子的数组(如果是这样,请不要忘记在您的视图中更改变量!)。

    【讨论】:

    • 如果它符合您的问题,您应该接受答案@mangotango2005
    【解决方案2】:
    def show
        @posts = current_user.posts
    end
    

    【讨论】:

      猜你喜欢
      • 2021-12-14
      • 2014-09-24
      • 2020-05-01
      • 1970-01-01
      • 2012-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-01
      相关资源
      最近更新 更多