首页 > 解决方案 > 用户如何在 Rails 中只查看自己的帖子?

问题描述

我只从帖子中随机显示一个帖子。

但我只想显示我发布的帖子,而不是整个帖子。(使用设计。)

我应该使用 cancancan 和 rolify gem 吗?

我想知道如何在不使用它的情况下做到这一点。

职位控制器

  def index
    @posts = Post.order("RANDOM()").first(1)
  end

index.html.erb

<% @posts.each do |x| %>
    <div class="xxx">
    <div class="boxcolor">
      <div class="boxcolor2" style="background-color:<%=x.color%>;"></div>
    </div>    
    <div class="boxtit"><%=x.title%></div> 
    <div class="boxcon"><%=x.content%></div> 
    </div>
<% end %>

标签: ruby-on-rails

解决方案


否则在控制器中使用它,它会在找不到当前用户 ID 时显示错误

before_action :authenticate_user!

并像这样进入索引操作

@posts = current_user.posts.order("RANDOM()").first(1)

推荐阅读