我已经正确地连接了hotwire/turbo,以便在页面的一个位置对单个模型执行crud操作,但我也希望在页面的不同位置同时更新相同的模型。我以为我可以只设置两个流,但它似乎不起作用。
指定目标确实适用于创建操作,这取决于我如何命名目标,但不适用于更新和销毁操作。这是我认为应该有效但不可行的方法:
-位置1(“生物”流)
<div id="creatures">
<%= turbo_stream_from "creatures" %>
<%= turbo_frame_tag "creatures" do %>
<div>
<% @creatures.each do |creature| %>
<div>
<%= render "creatures/creature", creature: creature %>
</div>
<% end %>
</div>
<% end %>
</div>-位置2 ("creatures_main“流)
<%= turbo_stream_from "creatures_main" %>
<%= turbo_frame_tag "creatures_main" do %>
<% @creatures.each do |creature| %>
<div>
<%= render "creatures/creature", creature: creature %>
</div>
<% end %>
<% end %>- common _creature.html.erb partial
<%= turbo_frame_tag dom_id(creature) do %>
<%= link_to creature.name, "#" %>
<% end %>- creature.rb
class Creature < ApplicationRecord
validates :name, presence: true
after_create_commit {
broadcast_append_to "creatures"
broadcast_append_to "creatures_main"
}
after_update_commit {
broadcast_replace_to "creatures"
broadcast_replace_to "creatures_main"
}
after_destroy_commit {
broadcast_remove_to "creatures"
broadcast_remove_to "creatures_main"
}
end当我在我的模型中有两个调用时,会发生什么情况是,创建操作将新创建的生物放在位置1两次,其中只有一次更新,但无论它们在页面上的什么位置,都会被正确销毁。
发布于 2021-04-05 16:58:48
creatures和creatures_main将是流名称。您正在寻找的是target和partial,它们控制流将在何处更新数据,以及它将使用哪个部分来更新。
您可以尝试:
after_create_commit -> {
# target here is the ID of the outer div, where data would be appended to
broadcast_append_to "creatures", target: "creatures"`
broadcast_append_to "creatures_main", target: "creatures_main"
}
after_update_commit {
# target here is the ID of each of the creature div
broadcast_replace_to "creatures", target: "creature_#{id}"
broadcast_replace_to "creatures_main", target: "creature_main_#{id}"
}
after_destroy_commit {
broadcast_remove_to "creatures"
broadcast_remove_to "creatures_main"
}<%= turbo_frame_tag "creature_#{creature.id}" do %>
<%= link_to creature.name, "#" %>
<% end %>
<%= turbo_frame_tag "creature_main_#{creature.id}" do %>
<%= link_to creature.name, "#" %>
<% end %>当然,这意味着如果在分词中有turbo_frame_tag,你可能需要使用两个不同的分词。您可以这样做:
after_update_commit {
# target here is the ID of each of the creature div
broadcast_replace_to "creatures", target: "creature_#{id}", partial: "creatures/creature", locals: {creature: self}
broadcast_replace_to "creatures_main", target: "creature_main_#{id}", partial: "creatures/creature_main", locals: {creature: self}
}顺便说一句,你应该使用这些方法的_later版本。为了更容易阅读,也可以使用render collection。
https://stackoverflow.com/questions/66724921
复制相似问题