首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ruby on rails turbo当前用户访问

Ruby on rails turbo当前用户访问
EN

Stack Overflow用户
提问于 2022-05-06 04:05:28
回答 1查看 214关注 0票数 0

index.html.erb

代码语言:javascript
复制
    <%= turbo_stream_from "posts" %>
     <%= turbo_frame_tag "posts" do %>
      <%= render partial:'posts/post', collection: @posts, as: :post %>
    <% end %>

_post.html.erb

代码语言:javascript
复制
  <% 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

代码语言:javascript
复制
after_create_commit -> {
    broadcast_prepend_to("posts")
}

当我为post after_create_commit做准备时,帖子被提前了,但是无法得到正确的Current.user。所以,这个<% if Current.user.id == post.user_id %>条件只在刷新后才能得到满足!帮我让它起作用!

EN

回答 1

Stack Overflow用户

发布于 2022-05-11 11:41:20

之所以会发生这种情况,是因为在turbo_stream中不能有对视图上下文的任何引用。视图上下文是当您在视图中时所处的对象,它有您喜欢使用的所有方法,比如帮助器。要解决这个问题,您需要更改变量的引用,然后将其传递到列表中,也可以在广播时传递。这最后看起来就像

代码语言:javascript
复制
 <%= render partial:'posts/post', collection: @posts, as: :post, current_user: Current.user %>

在回调中,您需要传递要更新的用户,因为您在这里无法访问Current.user。

代码语言:javascript
复制
broadcast_prepend_to("posts", locals: { current_user: user_to_update })

这是可行的,但它将要求您了解您正在更新的用户。

解决这个问题的另一个选择是从控制器端使用流响应,但是这只会更新当前用户的页面。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72136048

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档