How do I get the current absolute URL in Ruby on R

2018-12-31 17:11发布

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

The request.request_uri only returns the relative URL.

30条回答
笑指拈花
2楼-- · 2018-12-31 17:39

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

查看更多
旧时光的记忆
3楼-- · 2018-12-31 17:39

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
查看更多
与风俱净
4楼-- · 2018-12-31 17:40
(url_for(:only_path => false) == "/" )? root_url : url_for(:only_path => false)
查看更多
余生请多指教
5楼-- · 2018-12-31 17:41

You could use url_for(:only_path => false)

查看更多
无与为乐者.
6楼-- · 2018-12-31 17:41

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
查看更多
牵手、夕阳
7楼-- · 2018-12-31 17:41

You can either use

request.original_url 

or

"#{request.protocol}#{request.host_with_port}" 

to get the current URL.

查看更多
登录 后发表回答