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

后端 未结 30 2108
佛祖请我去吃肉
佛祖请我去吃肉 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:17

    Rails 4.0

    you can use request.original_url, output will be as given below example

    get "/articles?page=2"
    
    request.original_url # => "http://www.example.com/articles?page=2"
    
    0 讨论(0)
  • 2020-11-22 14:19

    I think that the Ruby on Rails 3.0 method is now request.fullpath.

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

    For rails 3 :

    request.fullpath

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

    Using Ruby 1.9.3-p194 and Ruby on Rails 3.2.6:

    If request.fullpath doesn't work for you, try request.env["HTTP_REFERER"]

    Here's my story below.

    I got similar problem with detecting current URL (which is shown in address bar for user in her browser) for cumulative pages which combines information from different controllers, for example, http://localhost:3002/users/1/history/issues.

    The user can switch to different lists of types of issues. All those lists are loaded via Ajax from different controllers/partials (without reloading).

    The problem was to set the correct path for the back button in each item of the list so the back button could work correctly both in its own page and in the cumulative page history.

    In case I use request.fullpath, it returns the path of last JavaScript request which is definitely not the URL I'm looking for.

    So I used request.env["HTTP_REFERER"] which stores the URL of the last reloaded request.

    Here's an excerpt from the partial to make a decision

    - if request.env["HTTP_REFERER"].to_s.scan("history").length > 0
      - back_url = user_history_issue_path(@user, list: "needed_type")
    - else
      - back_url = user_needed_type_issue_path(@user)
    - remote ||= false
    =link_to t("static.back"), back_url, :remote => remote
    
    0 讨论(0)
  • 2020-11-22 14:22

    To get the request URL without any query parameters.

    def current_url_without_parameters
      request.base_url + request.path
    end
    
    0 讨论(0)
  • 2020-11-22 14:23

    For Ruby on Rails 3:

    request.url
    request.host_with_port
    

    I fired up a debugger session and queried the request object:

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