我有一个标准资源:
resources :customers
在页面上"显示" (/customers/:id
)有一个链接指向其他客户。当我点击它时,如何检查引用者是否为/customers/:id
页面?我试着这样做:
[1] pry(#<CustomersController>)> URI(request.referer).path
=> "/customers/88" # previous ulr
[2] pry(#<CustomersController>)> customer_path
=> "/customers/98" # current url
但它不起作用。换句话说,:id
中的/customers/:id
始终会发生变化,那么如何检查URI(request.referer).path
是否属于customer_path
?
if URI(request.referer).path == ??? #???
答案 0 :(得分: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