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")
}当我为post after_create_commit做准备时,帖子被提前了,但是无法得到正确的Current.user。所以,这个<% if Current.user.id == post.user_id %>条件只在刷新后才能得到满足!帮我让它起作用!
发布于 2022-05-11 11:41:20
之所以会发生这种情况,是因为在turbo_stream中不能有对视图上下文的任何引用。视图上下文是当您在视图中时所处的对象,它有您喜欢使用的所有方法,比如帮助器。要解决这个问题,您需要更改变量的引用,然后将其传递到列表中,也可以在广播时传递。这最后看起来就像
<%= render partial:'posts/post', collection: @posts, as: :post, current_user: Current.user %>在回调中,您需要传递要更新的用户,因为您在这里无法访问Current.user。
broadcast_prepend_to("posts", locals: { current_user: user_to_update })这是可行的,但它将要求您了解您正在更新的用户。
解决这个问题的另一个选择是从控制器端使用流响应,但是这只会更新当前用户的页面。
https://stackoverflow.com/questions/72136048
复制相似问题