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..!
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
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
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