routes.rb中的request.env [“HTTP_USER_AGENT”]

时间:2013-12-04 21:21:00

标签: ruby-on-rails ruby

我正在尝试根据用户是否是机器人来提供不同的页面,所以我将此代码放在routes.rb文件中:

request.env["HTTP_USER_AGENT"].include? "bot"

并收到此错误:

block in <top (required)>': undefined local variable or method `request' for #<ActionDispatch::Routing::Mapper:0x007fe30f329f98> (NameError)

任何想法如何使我的工作?

环顾四周找到了这个,但它仍然给我一个错误:

constraints :user_agent => /bot/ do
    root :to => "events#index"
  end
  constraints :user_agent => /^((?!bot).)*$/ do
    root :to => "main#index"
  end

2 个答案:

答案 0 :(得分:2)

我想你想要routing constraints

例如:

# Routes matched in order specified, so this will be checked first
constraints :user_agent => /bot/ do
  root :to => "events#index", as: :bot_root
end

# If the above route didn't apply, this one should happen instead
root :to => "main#index"

as: :bot_root应该有助于避免根命名冲突

答案 1 :(得分:0)

您应该使用内置的:constraints参数进行路由。可以找到常规方法here,并且有一个很好的blog post,它解释了如何根据用户代理字符串进行过滤。看起来你可以放点像

get "/page" => "page#show", :bot => true, :constraints => {:user_agent => /bot/}
您的routes.rb文件中的