0

在我的程序中,一个Board可以有很多Sections. 我为此Boards#show列出了所有内容。一个用户可以为这个用户创建、编辑和删除。我使用 Pundit 进行授权。SectionsBoardSectionsBoards

我的问题是,将 AJAX 添加到创建Section操作后,我的策略检查不再起作用。AJAX 调用在Sections添加时工作正常,但“编辑”和“删除”链接仅在我重新加载页面后显示。

看板#show

<% if policy(@board).edit? %>
<p><strong>Create a new Section</strong></p>
  <%= render 'sections/shared/form', board: @board, section: @section %>
<% end %>
<br>

<p><strong>Sections</strong></p>
<div id="sections">
  <% @board.sections.order(id: :asc).each_with_index do |section, index| %>
    <span><%= "#{index + 1}. #{section.title}" %></span>
    <% if policy(section).edit? %>
      <%= link_to "Edit", edit_board_section_path(@board, @board.sections[index]) %>
    <% end %>
    <% if policy(section).destroy? %>
      <%= link_to("Delete", board_section_path(@board, @board.sections[index]), method: :delete) %>
    <% end %>
    <br>
  <% end %>
</div>

形成部分

<%= simple_form_for([@board, @section], remote: true, authenticity_token: true) do |f| %>
  <%= f.input :title, id: "section_title" %>
  <%= f.submit "Save" %>
<% end %>

AJAX 调用

var newSection = "<span><%= "#{@board.sections.length}. #{@section.title}" %></span><br>";

var sections = document.getElementById('sections');
sections.insertAdjacentHTML('beforeend', newSection);

var sectionTitle = document.getElementById('section_title');
sectionTitle.value = '';

我认为问题在于新创建Section的没有插入到循环中,因此无法检查策略。我该如何重构我的代码来解决这个问题?

4

1 回答 1

1

您应该能够将 HTML 模板呈现到您的js.erb文件中。请参阅 DHH https://signalvnoise.com/posts/3697-server-generated-javascript-responses的帖子如何正确使用它。这是一篇较旧的帖子,所以可能有些事情发生了变化,但您应该知道要搜索什么。但如果它仍然以这种方式工作,你应该能够做这样的事情:

将部分提取到部分_section.html.erb

    <span><%= "#{index + 1}. #{section.title}" %></span>
    <% if policy(section).edit? %>
      <%= link_to "Edit", edit_board_section_path(@board, @board.sections[index]) %>
    <% end %>
    <% if policy(section).destroy? %>
      <%= link_to("Delete", board_section_path(@board, @board.sections[index]), method: :delete) %>
    <% end %>
    <br>

Boards#show在您的文件中也使用此部分。

js.erb在文件中渲染你的部分

var newSection = "<span><%=j render @section %></span><br>";

像这样的东西应该可以工作,但我不使用服务器生成的 javascript,所以他们可能会改变一些东西。但希望它至少可以帮助你找到方向。

于 2019-08-10T12:01:13.573 回答