ambertch
ambertch

Reputation: 7649

url_for generates a url with current path inserted

I am generating a url in my controller accessed from the relative path "/hangouts/test", for a url on an external site (facebook). I want to use url_for and pass in params using hashes so it can escape them. The URL I want is this:

http://www.facebook.com/connect/prompt_permissions.php?api_key=6aca22e72866c7eaaedfb15be69c4b93&...

Using this, however:

url_for(:host => "www.facebook.com/connect/prompt_permissions.php?", :api_key => Facebooker.api_key, :next => test_hangouts_url, :cancel => root_url, :ext_perm  => "publish_stream")

I instead get my current path of /hangouts/test thrown in there:

http://www.facebook.com/connect/prompt_permissions.php/hangouts/test?api_key=6aca22e72866c7eaaedfb15be69c4b93&...

As you can see, I don't want "/hangouts/test" to be in there - played a bit with the options in the API docs but stumped, anybody know how to use url_for without it inserting the current path? Thanks!

Upvotes: 2

Views: 1652

Answers (2)

EmFi
EmFi

Reputation: 23450

You shouldn't be using the hash form of url_for to generate links outside of your application.

Instead you should just be using the string version form:

url_for "http://www.facebook.com/connect/prompt_permissions.php?api_key=6aca22e72866c7eaaedfb15be69c4b93&next=#{test_hangouts_url}&cancel=#{root_url}&ext_perm=publish_stream"

url_for will use the current action controller/action/id unless the hash given to url_for contains one of those arguments. url_for will then generate a url from a route that matches the arguments given in the hash. The arguments to url_for used in the question generates a valid url, because it can match a route using the current controller/action. You will not be able to generate the url you want with the hash form of url for without matching a route. Providing a controller in the hash you give url_for should match the default routes that rails generates for you when you create an application, but that's not very DRY.

The better solution is to use a named route:

map.prompt_fb_permissions "/connect/prompt_permissions.php", 
  :host => "www.facebook.com", :controller => nil, :action => nil

then you can use the following in place of url_for whenever you want to generate this this url.

prompt_fb_permissions(:api_key => Facebooker.api_key, :next => test_hangouts_url, 
  :cancel => root_url, :ext_perm  => "publish_stream")

Upvotes: 2

Randolpho
Randolpho

Reputation: 56439

You left out the controller parameter, which is why it's automatically adding your controller path ("/hangouts/test"), to your base host.

Try this:

url_for(:host => "www.facebook.com", :controller=> "/connect/prompt_permissions.php", :api_key => Facebooker.api_key, :next => test_hangouts_url, :cancel => root_url, :ext_perm  => "publish_stream")

Upvotes: 0

Related Questions