我正在尝试通过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/