LoginSignup
16
14

More than 5 years have passed since last update.

Railsのconfig/route.rbで別サイトにリダイレクトさせる際の注意点

Last updated at Posted at 2012-03-24

Railsのroute設定では別URLへのリダイレクトを記述できるが、ちょっとしたpitfallがあるので書いておく

リダイレクト記述は下記のようになる

routes.rb
 get "foo/:id" => redirect("http://othersite.com/foo/%{id}",:status => 301 )

ここで問題はこの記述を書く位置である。若干Railsのバグっぽい挙動があり、例えばlink_toなどのハッシュ型のリンク記述でidがあると上記とマッチしてしまうという現象がある。

つまり

<%= button_to "POST",:controller => "bar",:action => "foo",:id => 12  %>

のようなリンクがある場合、下記のようにリダイレクトのものが先にくると、困ったことにそれにマッチしていると認識されるようである

route.rb
get "foo/:id" => redirect("http://othersite.com/foo/%{id}",:status => 301)
post "foo/:id" => "foo#bar"

結果としては意図しない外部サイトへのリダイレクトに遭遇することとなる。

よって外部サイトのredirectはroute.rbの最後に書くのが安全そうである。

ちなみにroutingのテストはfunctionalsテストとして下記のように書ける

foo_controller_test.rb
assert_routing "/foo/123",{:controller =>"bar",:action =>"foo",:id => "123"}
assert_routing {:method => :post,:path => "/foo"},{:controller => "bar",:action => "foo"}

現時点ではredirectを持つroutingのテスト方法は不明(stack overflowで質問中)だが、それ以外だけでも丁寧に書いておけば妙なハマりを未然に防げるだろう。

16
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
14