首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何检查通过AJAX创建的对象的策略

如何检查通过AJAX创建的对象的策略
EN

Stack Overflow用户
提问于 2019-08-10 18:53:48
回答 1查看 91关注 0票数 0

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

我的问题是,在将AJAX添加到create Section操作之后,我的策略检查不再有效。AJAX调用工作正常,因为添加了Sections,但只有在重新加载页面后才会显示“编辑”和“删除”链接。

Boards#show

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

部分表单

代码语言:javascript
运行
复制
<%= simple_form_for([@board, @section], remote: true, authenticity_token: true) do |f| %>
  <%= f.input :title, id: "section_title" %>
  <%= f.submit "Save" %>
<% end %>

AJAX调用

代码语言:javascript
运行
复制
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没有插入到循环中,因此无法检查策略。我如何重构我的代码来解决这个问题呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-10 20:01:14

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

将部分解压缩为部分_section.html.erb

代码语言:javascript
运行
复制
    <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文件中呈现部分内容

代码语言:javascript
运行
复制
var newSection = "<span><%=j render @section %></span><br>";

这样的东西应该可以工作,但是我没有使用服务器生成的javascripts,所以它们可能改变了一些东西。但希望它至少能在方向上对你有所帮助。

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

https://stackoverflow.com/questions/57441478

复制
相关文章

相似问题

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