Full URL with url_for in Rails

前端 未结 6 1581
别那么骄傲
别那么骄傲 2020-12-28 15:34

How can I get a full url in rails?

url_for @book is returning only a path like /book/1 and not www.domain.com/book/1

Thanks (and sorry if the answer is obvio

6条回答
  •  清歌不尽
    2020-12-28 16:12

    In Rails 5, if you want the full url for the current controller/action (== current page), just use:

    url_for(only_path: false)
    

    Long answer:

    In Rails 5, url_for in a view is ActionView::RoutingUrlFor#url_for. If you look at it's source code (https://api.rubyonrails.org/classes/ActionView/RoutingUrlFor.html#method-i-url_for), you'll see if you pass a Hash (keyword parameters are cast into a Hash by Ruby), it actually calls super, thus invoking the method of same name in it's ancestor.

    ActionView::RoutingUrlFor.ancestors reveals that it's first ancestor is ActionDispatch::Routing::UrlFor.

    Checking it's source code (https://api.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html#method-i-url_for), you'll read this:

    Missing routes keys may be filled in from the current request's parameters (e.g. :controller, :action, :id and any other parameters that are placed in the path).

    This is very nice, since it will build automatically a URL for you for the current page (or path, if you just invoke url_for without the only_path: false). It will also intelligently ignore the query string params; if you need to merge those, you can use url_for(request.params.merge({arbitrary_argument:'value'})).

提交回复
热议问题