Full URL with url_for in Rails

前端 未结 6 1557
别那么骄傲
别那么骄傲 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 15:59

    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.

提交回复
热议问题