How do I get the current absolute URL in Ruby on Rails?

后端 未结 30 2107
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 13:47

How can I get the current absolute URL in my Ruby on Rails view?

The request.request_uri only returns the relative URL

相关标签:
30条回答
  • 2020-11-22 14:24

    You can add this current_url method in the ApplicationController to return the current URL and allow merging in other parameters

    # https://x.com/y/1?page=1 
    # + current_url( :page => 3 )
    # = https://x.com/y/1?page=3
    def current_url(overwrite={})
        url_for :only_path => false, :params => params.merge(overwrite)
    end
    

    Example Usage:

    current_url --> http://...
    current_url(:page=>4) --> http://...&page=4
    
    0 讨论(0)
  • 2020-11-22 14:24

    To get the absolute URL which means that the from the root it can be displayed like this

    <%= link_to 'Edit', edit_user_url(user) %>
    

    The users_url helper generates a URL that includes the protocol and host name. The users_path helper generates only the path portion.

    users_url: http://localhost/users
    users_path: /users
    
    0 讨论(0)
  • 2020-11-22 14:25

    For Rails 3.2 or Rails 4+

    You should use request.original_url to get the current URL.

    This method is documented at original_url method, but if you're curious, the implementation is:

    def original_url
      base_url + original_fullpath
    end
    

    For Rails 3:

    You can write "#{request.protocol}#{request.host_with_port}#{request.fullpath}", since request.url is now deprecated.


    For Rails 2:

    You can write request.url instead of request.request_uri. This combines the protocol (usually http://) with the host, and request_uri to give you the full address.

    0 讨论(0)
  • 2020-11-22 14:25

    If by relative, you mean just without the domain, then look into request.domain.

    0 讨论(0)
  • 2020-11-22 14:25

    You can use the ruby method:

    :root_url
    

    which will get the full path with base url:

    localhost:3000/bla
    
    0 讨论(0)
  • 2020-11-22 14:25

    In Rails 3 you can use

    request.original_url
    

    http://apidock.com/rails/v3.2.8/ActionDispatch/Request/original_url

    0 讨论(0)
提交回复
热议问题