1

I’m following this tutorial to implement a feature where user can submit Trivia/Interesting Facts.

I want to restrict (edit/delete) functionality to the admin or author of each item.



I’ve created a helper class in .application_controller

def author_of?(resource)
user_signed_in? && current_user.id == resource.user_id
end

But when I'm using this in Turbo-frame with Hotwire I’m getting this error

| ActionView::Template::Error (Devise could not find the Warden::Proxy instance on your request environment.

Here's my code for reference

index.html

<%= turbo_stream_from @stadium, :trivia %>
<%= tag.div id: "#{dom_id(@stadium)}_trivia" do %>
    <%= render partial: "trivia/trivium", collection: @stadium.trivia %>
<% end %>
<% end %>

_trivium.html.erb

<%= turbo_frame_tag trivium do %>

<%= trivium.body %>

<% if author_of?(trivium) || admin? %>
<%= button_to "Delete", trivium_path(trivium), class: "btn btn-small btn-danger btn-link mr-2", method: :delete, data: { confirm: "Are you sure?" } %>
<% end %>

<% end %>

How can I access the current_user helper in the comment partial to check if the current_user is the author or admin (and should be allow to delete/edit)?

tommers
  • 51
  • 7

1 Answers1

1

The reason this errors is, as mentioned here, partials with Turbo frames are rendered without any of your global helpers available.

That SO question points to a Hotwire forum here where they discuss possible solutions. The best one in my view is described here.

The gist is:

  • Pass in current_user as an argument to your partial, rather than accessing it from within your partial
  • Do your permission check within the partial, rather than the helper
<%= render partial: "trivia/trivium", collection: @stadium.trivia, user: current_user %>

You might consider turning your author_of method into a model method as well, and then you'll have the option to use it within your partial.

aidan
  • 1,627
  • 17
  • 27