Luka Kerr Luka Kerr - 5 months ago 8
Ruby Question

Devise Authentication Not Hiding Update/Destroy Buttons

Im using the Devise gem with rails and I have an Item page with buttons that link to

Home
Edit
and
Destroy
. If a user who hasn't created the item tries to edit or destroy the item, then they get an error message and the item doesnt get edited or destroyed.

Although, I would like it so that if a user who hasn't created a specific item is logged in, they cannot view the Edit or Destroy buttons on that item.

Currently I have this if statement which I thought would work, but it only works if a user isn't signed in at all. If someone is signed in who did not create the item, they can still view the edit and destroy buttons.

show.html.erb if statement:

<%= link_to "Home", root_path, class: "btn btn-sm btn-default" %>
<% if current_user %>
<%= link_to "Edit", edit_item_path(@item), class: "btn btn-sm btn-default" %>
<%= link_to "Delete", item_path(@item), method: :delete, data: { confirm: "Are you sure?" }, class: "btn btn-sm btn-default" %>
<% end %>


And in the Items controller these are the before properties:

before_action :find_item, only: [:show, :edit, :update, :destroy]
before_action :authorized_user, only: [:edit, :update, :destroy]
before_filter :authenticate_user!, except: [:index, :show]


Create Method in controller:

def create
@item = current_user.items.build(items_params)

if @item.save
redirect_to @item
else
render "new"
end
end


The controller works as it should, preventing users who aren't signed in, or didnt create the item not to be able to delete or edit it. Although the buttons can still be clicked on if a user is signed in, but didnt create the item.

Anyone know how to help?

Answer

Show links only if user signed in and has created the item.

You didn't provided your model assosiations for more detailed answer but try to do the next:

<%= link_to "Home", root_path, class: "btn btn-sm btn-default" %>
  <% if current_user && @item.created_by(current_user)%>
    <%= link_to "Edit", edit_item_path(@item), class: "btn btn-sm btn-default" %>
    <%= link_to "Delete", item_path(@item), method: :delete, data: { confirm: "Are you sure?" }, class: "btn btn-sm btn-default" %>
  <% end %>

Please be noted that I just assumed you have method like this @item.created_by(current_user)

UPDATE

That should work

<%= link_to "Home", root_path, class: "btn btn-sm btn-default" %>
  <% if current_user && current_user.items.include?(@item)%>
    <%= link_to "Edit", edit_item_path(@item), class: "btn btn-sm btn-default" %>
    <%= link_to "Delete", item_path(@item), method: :delete, data: { confirm: "Are you sure?" }, class: "btn btn-sm btn-default" %>
  <% end %>