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:44

This works for Ruby on Rails 3.0 and should be supported by most versions of Ruby on Rails:

request.env['REQUEST_URI']
查看更多
弹指情弦暗扣
3楼-- · 2018-12-31 17:46
 url_for(params)

And you can easily add some new parameter:

url_for(params.merge(:tag => "lol"))
查看更多
弹指情弦暗扣
4楼-- · 2018-12-31 17:46

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
查看更多
后来的你喜欢了谁
5楼-- · 2018-12-31 17:48

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.

查看更多
无色无味的生活
6楼-- · 2018-12-31 17:48

To get the request URL without any query parameters.

def current_url_without_parameters
  request.base_url + request.path
end
查看更多
君临天下
7楼-- · 2018-12-31 17:48

You can set a variable to URI.parse(current_url), I don't see this proposal here yet and it works for me.

查看更多
登录 后发表回答