1

我有一个标准资源:

resources :customers

在“显示”页面 ( /customers/:id) 上有一个指向其他客户的链接。当我点击它时,我如何检查referer是否是/customers/:id页面?我试图这样做:

[1] pry(#<CustomersController>)> URI(request.referer).path
=> "/customers/88" # previous ulr

[2] pry(#<CustomersController>)> customer_path
=> "/customers/98" # current url

但它不起作用。换句话说,:idin/customers/:id总是在变化,那么我如何检查是否 URI(request.referer).path属于customer_path

if URI(request.referer).path == ??? #???
4

1 回答 1

2

这将起作用,但远非漂亮。然而,它非常灵活,并且在生成的 url 助手上进行中继,因此如果您决定更改 url 映射,则不应中断。

if URI(request.referer).path =~ Regexp.new(customer_path(':customer_id').gsub(':customer_id', '\d+'))

很多很多更好的解决方案:

Rails 应用程序有一个方法可以识别路径并返回控制器/动作:

Rails.application.routes.recognize_path(URI(request.referer).path)
#=> {:controller => 'customers', :action => 'show', :id => '88'}

您可以使用它来编写辅助方法:

def is_referer_customer_show_action?
  referer_url = Rails.application.routes.recognize_path(URI(request.referer).path)
  referer_url[:controller] == 'customers' && referer_url[:action] == 'show'
end
于 2014-04-13T16:32:18.327 回答