Full URL with url_for in Rails

In Rails 4, url_for only takes one argument, so you need to pass an array with an explicit hash inside for the only_path option.

Good:

url_for([@post, @comment, {only_path: true}])

Bad:

url_for(@post, @comment, {only_path: true})
url_for([@post, @comment], {only_path: true})

From the source, url_for with an Array input just calls:

polymorphic_url([@post, @comment], {only_path: true})

as shown in @moose's answer.

As noted by @lime, only_path is generally not needed for polymorphic_url since you distinguish that with the _url _path suffixes.


It seems that this would work:

url_for(@book)

But it does not. The url_for method accepts only one argument, which can be either a string, an instance of a model, or a hash of options. This is rather unfortunate, as it would seem like you may need to link to @book and add options like :only_path or :host as well.

One way around it is to use polymorphic_url, which would render the correct absolute url even though your model is (likely) not actually polymorphic:

polymorphic_url(@book, :host => "domain.com")

Perhaps the best route would be to use a named route, which is set up automatically for you when declaring resources in your routes or using the :as option:

# in routes.rb:
resources :books
# or
get "books/:id" => "books#show", as: :book

# in your view:
book_path(@book, :host => "domain.com")

According to the docs, this shouldn't happen. The option you're looking for is :only_path and it's false by default. What happens if you set it to false explicitly?

url_for(@book, :only_path => false)

While you can use url_for you should prefer Ryan's method when you can - book_url(@book) for a full url or book_path(@book) for the path.


If it's a RESTful resource you'll be able to use this:

book_url(@book)