处理带有restfull路由的错误消息的表单时,link_to_unless_current失败

有谁知道如何防止link_to_unless_current的失败机制?

fe:我有我的页面导航

link_to_unless_current "new task", new_task_path 

当我点击链接时,我来到新的taks路径表单…并且没有创建链接 – >确定。 然后我在表单中输入错误的值并提交。

TasksController处理“创建”操作,ActiveRecord模型的validation因数据不正确而失败,并且控制器呈现“新”操作(并包含模型的错误消息)。

 class TasksController  "new" end end end 

但是这里链接被创建了! – >由于url之间的区别:

  link path = new_task_path 

  posted path = tasks_path with :method => :post 

有人知道如何彻底解决这个问题吗?

谢谢

快速浏览link_to_unless_current的源代码……

…它使用current_path? 这样你就可以做到这样的事情:

在帮手……

 def current_page_in?(*pages) pages.select {|page| current_page?(page)}.compact.any? end 

…然后在你的视图中,你可以提供一个像named_routes或哈希的数组,如Shadwell的答案。

 <%= link_to_unless(current_page_in?(new_thing_path, things_path), "add a thing") %> 

你明白了……

更新

想想这个……如果你可以像你希望原始方法一样工作,那就太好了。 在这里,我们将提供的命名路由(或控制器+动作哈希)与当前页面及其引用者进行比较。

 def current_page_or_referrer_in(options) url_string = CGI.unescapeHTML(url_for(options)) request = @controller.request # We ignore any extra parameters in the request_uri if the # submitted url doesn't have any either. This lets the function # work with things like ?order=asc if url_string.index("?") request_uri = request.request_uri referrer_uri = request.referrer else request_uri = request.request_uri.split('?').first referrer_uri = request.referrer.split('?').first end #referrer_uri always has full path (protocol, host, port) so we need to be sure to compare apples w apples if url_string =~ /^\w+:\/\// ["#{request.protocol}#{request.host_with_port}#{request_uri}", referrer_uri].include?(url_string) else referrer_uri = referrer_uri.gsub(request.protocol, '').gsub(request.host_with_port, '') [request_uri, referrer_uri].include?(url_string) end end 

美丽的是它现在让你这样做(从你的例子):

 <%= link_to_unless(current_page_or_referrer_in(new_task_path), "Add a task") %> 

然后它将显示您是否在new_task_path或已发送的页面(例如创建页面)

您可以使用link_to_unless而不是link_to_unless_current来执行此操作:

 link_to_unless(controller_name == 'tasks' && (action_name == 'new' || action_name == 'create'), new_task_path)