用户如何在Rails中仅查看自己的帖子?

时间:2018-08-23 10:39:56

标签: ruby-on-rails

我只随机显示一个帖子。

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

我应该使用cancancan并使其宝石化吗?

我想知道如何不使用它。

帖子控制器

  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 %>

2 个答案:

答案 0 :(得分:1)

将其用于控制​​器中,否则,当未找到当前用户ID时会显示错误

before_action :authenticate_user!

并进入索引操作,就像这样

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

答案 1 :(得分:0)

这是您必须执行的操作。

routes.rb

devise_for :users

resources :posts, only: :index

user.rb

class User < ActiveRecord::Base
  has_many :posts
end

post.rb

class Post < ActiveRecord::Base
  belongs_to :user
end

posts_controller.rb

class PostsController < ApplicationController
  before_action :authenticate_user!

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

end
相关问题