Jill
Jill

Reputation: 441

Ruby-On-Rails How to allow only current user to edit and delete posts they have created

I am making a blog application and when the user is viewing the post index view I want them to only edit and delete posts they have created. I am getting the following error:

undefined method `user_id' for nil:NilClass

views/posts/index.html

    <td><% if current_user.id == @post.user_id %></td>
        <td><%= link_to 'Edit', edit_post_path(@post) %></td>
        <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
        <% end %>

The above is my if statement that allows user to only edit and delete posts they have created.

create method in post_controller:

def create
    @post = Post.new(post_params)
    @post.user = current_user

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render :show, status: :created, location: @post }
      else
        format.html { render :new }
        form

at.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

Upvotes: 1

Views: 2536

Answers (2)

Thor odinson
Thor odinson

Reputation: 180

you want to make sure that the if statement is out side of the TD tag

    <% if current_user && current_user.id == @post.user_id %>
      <td></td>
      <td><%= link_to 'Edit', edit_post_path(@post) %></td>
      <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
    <% end %>



 #Post Controller 
  class Post < ApplicationController
    ...
    def show
      @post = Post.find(params[:id])
    end
    ...
  end

Upvotes: 1

Alexander Luna
Alexander Luna

Reputation: 5439

I do a before action filter for the edit, update and destroy action:

before_action :correct_user, only: [:edit, :update, :destroy]

def correct_user
    @post = Post.find_by(id: params[:id])  // find the post
    unless current_user?(@post.user)
      redirect_to user_path(current_user)
    end
  end

current_user?(@post.user) this checks if the current_user and the @post.user that you defined when you create a new post are the same.

In my sessionHelper I have to methods for defining the current user:

  def current_user?(user)
    user == current_user
  end

  def current_user
    if(user_id = session[:user_id])
      @current_user ||= User.find_by(id: user_id)
    end
  end

In your post view you have to add conditional code to render the edit and delete links only if the user is the correct one:

<% if current_user?(post.user) %>
          <%= link_to "Edit", edit_micropost_path(micropost) %>
          <%= link_to "Delete", micropost, method: :delete, data: { confirm: "Do you want to delete this post ?"}%>
          <% end %>

Upvotes: 2

Related Questions