2011-12-29 64 views
1

拥有2个模型customer和comm_log。它们的关联如下:如何在rails 3.1中的link_to中构造删除路由?

resources :customers do 
    comm_logs 
end 

在comm_logs控制器中销毁的rspec代码没有任何错误地传递。 lambda模块验证成功删除后,通讯记录数减1。控制器中的一切看起来都是正确

耙路线的输出是:

 new_customer_comm_log GET /customers/:customer_id/comm_logs/new(.:format)     {:action=>"new", :controller=>"comm_logs"} 
     edit_customer_comm_log GET /customers/:customer_id/comm_logs/:id/edit(.:format)   {:action=>"edit", :controller=>"comm_logs"} 
      customer_comm_log GET /customers/:customer_id/comm_logs/:id(.:format)     {:action=>"show", :controller=>"comm_logs"} 
          PUT /customers/:customer_id/comm_logs/:id(.:format)     {:action=>"update", :controller=>"comm_logs"} 
          DELETE /customers/:customer_id/comm_logs/:id(.:format)     {:action=>"destroy", :controller=>"comm_logs"} 

在现实中,记录不点击删除按钮后删除,因为它是在控制器(显示页面的页面没有重定向到前一页只是保持不变,删除后没有重定向到任何地方)。看来,删除操作被路由到了正确的路径。问题很可能是以下视图中的link_to:

<%= link_to 'delete', customer_comm_log_path(@customer, @comm_log), :method => :delete, :confirm => "are you sure?", :remote => true %> 

link_to上面有什么问题吗?谢谢。

+0

你可以发布你的控制器销毁方法吗? – andrewpthorp 2011-12-29 18:23:42

回答

1

有几件事你可能会错过。我假设你使用jQuery,因为你没有在你的问题中指定。

一)请确保您有jQuery的安装

二)确保已手动安装了Rails UJS(不显眼的JavaScript)的适配器或使用宝石(为Rails 3.1说明这个链接以及): https://github.com/rails/jquery-ujs

C)你link_to需要告诉Rails的UJS适配器,它应该抓住该链接的点击,并通过AJAX

<%= link_to 'delete', customer_comm_log_path(@customer, @comm_log), :remote => true, :method => :delete) %> 

所以提交DELETE请求在上面的link_to,你失踪:remote => true

Rails会捕获链路上的用户的点击,然后揭开序幕一个jQuery $.ajax呼叫到您的服务器,其中包括一对夫妇PARAMS告诉Rails的服务器,这是一个远程DELETE请求。

d)如果您通过用户单击类似的远程链接重定向到控制器,您需要通过将此代码放置在您的ApplicationController中来告诉Rails正确处理AJAX重定向。如果你不这样做,链接将删除记录,但它只会坐在那里,而不是重定向。

# Allows redirecting for AJAX calls as well as normal calls 
    def redirect_to(options = {}, response_status = {}) 
    if request.xhr? 
     render(:update) {|page| page.redirect_to(options)} 
    else 
     super(options, response_status) 
    end 
    end 
+0

我正在运行rails 3.1.0,jquery似乎已经安装。 Gemfile中有gem'jquery-rail'。在application.js中,需要jquery并且需要jquery.ui。刚刚添加jquery.ujs。在post中添加了def代码,以便将ajax重定向到application_controller.rb。除了:remote => true,还添加了:confirm => true的link_to。点击删除时没有启动确认。没有重定向。记录仍然存在。 – user938363 2011-12-29 19:04:13

+0

服务器日志说什么(即请求曾经触及服务器)?此外,请检查您的浏览器的控制台的JavaScript错误。如果你有JS错误,那么它不会执行'$ .ajax'调用。 – iwasrobbed 2011-12-30 00:59:54

+0

创建new.js.erb文件并在lease_logs控制器中添加了带有html和js格式的respond_to后,上面发布的ajax destroy开始工作。 new.js.erb中有两行:$(“<%= escape_javascript render(:file =>'lease_logs/new.html.erb')%>”)。insertAfter( '#new_log_link'); $('#new_log_link')。hide(); – user938363 2012-01-03 17:29:33