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

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

提交回复
热议问题