在我的程序中,一个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的没有插入到循环中,因此无法检查策略。我该如何重构我的代码来解决这个问题?