javascript - 尝试通过ajax销毁ruby on Rails中关系实体的请求

标签 javascript ruby-on-rails ajax

我正在尝试通过ajax请求删除“预算”(葡萄牙语“orçamento”),并且预算与地籍有关系,而地籍有很多预算。我的组件如下:

orcamentos_controller.rb

.
.
.

    def destroy
            @cadastro = Cadastro.find(params[:cadastro_id])
            @orcamento = @cadastro.orcamentos.find(params[:orcamento_id])
            @orcamento.destroy

            respond_to do |format|
                format.js { head :ok }
            end
    end

    def index
        @cadastro = Cadastro.find(params[:cadastro_id])
        @orcamentos = @cadastro.orcamentos.paginate(page: params[:page], per_page: 10)
    end
.
.
.

index.html.erb

... <%= render "orcamentos_lista" %> ...

_orcamentos_lista.html.erb

<table class="table">
    <% @orcamentos.each do |orcamento| %>
      <tr id="remove_orcamento_<%= orcamento.id %>">
          <td>
              <%= link_to "Orçamento nº #{orcamento.id}, registrado em #{orcamento.created_at.strftime("%d/%m/%Y")}", "#", class: "list-group-item", type: 'button'%>
          </td>
          <td>
              <%= link_to "Excluir", orcamento, method: :destroy, remote: true %>
          </td>
      </tr>
    <% end %>
</table>

<% content_for :js do %>
  <% @orcamentos.each do |orcamento| %>
    $('#remove_orcamento_<%= orcamento.id %>').bind('ajax:success',
     function(){
       $('#orcamento_<%=orcamento.id%>').remove();
     }
    );
  <% end %>
<% end %>

路线.rb

.
.
.
    resources :cadastros do
      resources :orcamentos
    end
.
.
.

我收到错误 undefined method orcamento_path for #<#<Class:0x007f5f39757930>:0x007f5f39cf1eb8>这条线<%= link_to "Excluir", orcamento, method: :destroy, remote: true %>

我是 ruby​​ 和 Rails 的初学者,所以请原谅我代码中的任何丑陋之处。

最佳答案

运行

rake routes 

然后,无论您希望该链接包含什么路径,都可以在路由表中找到它,并在末尾使用“前缀”和“_path”。因此,如果您想要的资源位于该表上并且具有 foo_bar 前缀,那么您的 link_to 应该在 View 中使用 foo_bar_path

所以改变这一行

<%= link_to "Excluir", orcamento, method: :destroy, remote: true %>

到此

<%= link_to "Excluir", foo_bar_path, method: :destroy, remote: true %>

关于javascript - 尝试通过ajax销毁ruby on Rails中关系实体的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34365200/

相关文章:

Javascript 如何手动启动 Star Promise Chain 执行

ruby-on-rails - Ruby on Rails 4 Redis 重用模型

ruby-on-rails - 检查比特币地址是否有效?

php - 如果您刷新 AJAX 请求的内容 (ob_flush),该内容将被加载?

javascript - 使用来自 JavaScript (D3r) 的警报将​​数据传递给 R

javascript - 是否有任何 Mongoose 验证库?

javascript - 通过 JavaScript 在图像点击上创建 URL

ruby-on-rails - 将新页面添加到 Rails 4 应用程序中

javascript - 是否可以在 Node js 中操作 DOM?

jquery - 按标题属性排除 anchor 。 - Ajax