Full URL with url_for in Rails

前端 未结 6 1582
别那么骄傲
别那么骄傲 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:14

    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")
    

提交回复
热议问题