Ruby on rails turbo current user access

718 views Asked by At

index.html.erb

    <%= turbo_stream_from "posts" %>
     <%= turbo_frame_tag "posts" do %>
      <%= render partial:'posts/post', collection: @posts, as: :post %>
    <% end %>

_post.html.erb

  <% if Current.user.id == post.user_id %>
    <div class="d-flex justify-content-between">
      <%= link_to edit_post_path(post), title:'Edit', class:"text-secondary",data: { turbo: false } do %>
        <i class="fa-solid fa-pen-to-square fs-3"></i>
      <% end %>
      <%= button_to post, method: :delete, class:'btn btn-danger',title:'Delete' do %>
      <i class="fa-solid fa-trash-can"></i>
      <% end %>
    </div>
  <% end %>

post.rb

after_create_commit -> {
    broadcast_prepend_to("posts")
}

When I prepend the post after_create_commit the post is getting prepended but not able to get the correct Current.user. So, this <% if Current.user.id == post.user_id %> condition is getting satisfied after refresh only! Help me to make it work..!

1

There are 1 answers

0
yungindigo On

The reason why this is happening is because in a turbo_stream you cannot have any references to the view context. The view context is the object you are in when you are inside of views this has all the methods you like to use like helpers. To fix this you need to change that reference for a variable and then pass it in in the list and also when you broadcast. This would end up looking like

 <%= render partial:'posts/post', collection: @posts, as: :post, current_user: Current.user %>

and in the callback you need to pass in the user you want to update to because you won't have access to Current.user here

broadcast_prepend_to("posts", locals: { current_user: user_to_update })

This would work but it would require you to know about the user you are updating.

Another option to get around this is to use a turbo_stream response from the controller side but this will only update the page for the current user