在我的程序中,一个Board
可以有多个Sections
。在Boards#show
上,我列出了此Sections
的所有Board
。用户可以为该用户创建的Boards
创建、编辑和删除Sections
。我使用Pundit来进行授权。
我的问题是,在将AJAX添加到create Section
操作之后,我的策略检查不再有效。AJAX调用工作正常,因为添加了Sections
,但只有在重新加载页面后才会显示“编辑”和“删除”链接。
Boards#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
没有插入到循环中,因此无法检查策略。我如何重构我的代码来解决这个问题呢?
发布于 2019-08-10 20:01:14
您应该能够将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>";
这样的东西应该可以工作,但是我没有使用服务器生成的javascripts,所以它们可能改变了一些东西。但希望它至少能在方向上对你有所帮助。
https://stackoverflow.com/questions/57441478
复制相似问题