dsfdsf2fafad
dsfdsf2fafad

Reputation: 321

How can users view only their own posts in Rails?

I only show one post at random from the post.

But I want to show only the posts I made, not the whole posts. (using Devise.)

Should I use cancancan and rolify gem?

I wonder how to do it without using it.

posts controller

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

Upvotes: 0

Views: 1109

Answers (2)

Here is how you'll have to do it.

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

Upvotes: 0

fool-dev
fool-dev

Reputation: 7777

Use this into the controller otherwise, it shows an error while don't found the current user ID

before_action :authenticate_user!

and into index action use like this

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

Upvotes: 2

Related Questions