Program Tip

Ruby on Rails에서 현재 절대 URL을 얻으려면 어떻게해야합니까?

programtip 2020. 9. 27. 13:47
반응형

Ruby on Rails에서 현재 절대 URL을 얻으려면 어떻게해야합니까?


Ruby on Rails보기에서 현재 절대 URL어떻게 얻을 수 있습니까?

request.request_uri단지 상대 URL을 반환합니다.


Rails 3.2 또는 Rails 4+의 경우

request.original_url현재 URL을 얻으려면을 사용해야 합니다.

이 메소드는 original_url method에 문서화되어 있지만 궁금한 점이 있다면 구현은 다음과 같습니다.

def original_url
  base_url + original_fullpath
end

Rails 3 :

당신은 쓸 수 "#{request.protocol}#{request.host_with_port}#{request.fullpath}"있기 때문에, request.url지금은 사용되지 않습니다.


Rails 2 :

request.url대신 쓸 수 있습니다 request.request_uri. 이것은 프로토콜 (일반적으로 http : //)을 호스트와 결합하고 request_uri를 사용하여 전체 주소를 제공합니다.


Ruby on Rails 3.0 방법은 이제 request.fullpath.


당신은 사용할 수 있습니다 url_for(:only_path => false)


지원 중단 경고 : #request_uri 사용은 지원 중단되었습니다 . 대신 fullpath를 사용하십시오.


당신이 사용하는 경우 레일 3.2 또는 레일 (4) 당신이 사용해야 request.original_url현재의 URL을 얻을 수 있습니다.


메소드에 대한 문서는 http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-original_url에 있지만 궁금한 경우 구현은 다음과 같습니다.

def original_url
  base_url + original_fullpath
end

current_url 메서드를 ApplicationController에 추가 하여 현재 URL을 반환하고 다른 매개 변수에서 병합을 허용 할 수 있습니다.

# 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

사용 예 :

current_url --> http://...
current_url(:page=>4) --> http://...&page=4

Ruby on Rails 3 :

request.url
request.host_with_port

디버거 세션을 시작하고 요청 개체를 쿼리했습니다.

request.public_methods

Ruby on Rails 3.1.0.rc4에서 :

 request.fullpath

응용 프로그램 URL이 필요 했지만 하위 디렉토리가 있습니다. 나는 사용했다 :

root_url(:only_path => false)

 url_for(params)

몇 가지 새로운 매개 변수를 쉽게 추가 할 수 있습니다.

url_for(params.merge(:tag => "lol"))

request.domain이 작동한다고 생각하지만 blah.blah.com과 같은 하위 디렉토리에 있다면 어떻게 될까요? 다음과 같이 작동 할 수 있습니다.

<%= request.env["HTTP_HOST"] + page = "/" + request.path_parameters['controller'] + "/" + request.path_parameters['action'] %>

경로 구조에 따라 매개 변수를 변경하십시오.

도움이 되었기를 바랍니다.


request_uriRuby on Rails 3에서 더 이상 사용되지 않는 것 같습니다 .

Using #request_uri is deprecated. Use fullpath instead.

Ruby 1.9.3-p194 및 Ruby on Rails 3.2.6 사용 :

경우 request.fullpath가 당신을 위해 작동하지 않습니다, 시도 request.env를 [ "HTTP_REFERER"]

여기 내 이야기가 있습니다.

예를 들어 다른 컨트롤러의 정보를 결합하는 누적 페이지에 대해 현재 URL (브라우저의 사용자 주소 표시 줄에 표시됨)을 감지하는 것과 비슷한 문제가 발생했습니다 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

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

request.env['REQUEST_URI']

None of the suggestions here in the thread helped me sadly, except the one where someone said he used the debugger to find what he looked for.

I've created some custom error pages instead of the standard 404 and 500, but request.url ended in /404 instead of the expected /non-existing-mumbo-jumbo.

What I needed to use was

request.original_url

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


(url_for(:only_path => false) == "/" )? root_url : url_for(:only_path => false)

You can use the ruby method:

:root_url

which will get the full path with base url:

localhost:3000/bla

In Rails 3 you can use

request.original_url

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


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"

you can use any one for rails 3.2:

request.original_url
or
request.env["HTTP_REFERER"]
or
request.env['REQUEST_URI']

I think it will work every where

"#{request.protocol}#{request.host}:#{request.port}#{request.fullpath}"

For Rails 3.2 or Rails 4 Simply get in this way "request.original_url" Reference: Original URL Method

For Rails 3 As request.url is deprecated.We can get absolute path by concatenating

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

For Rails 2

request.url

if you want to be specific, meaning, you know the path you need:

link_to current_path(@resource, :only_path => false), current_path(@resource)

For rails 3 :

request.fullpath


request.env["REQUEST_URI"]

works in rails 2.3.4 tested and do not know about other versions.


To get the request URL without any query parameters.

def current_url_without_parameters
  request.base_url + request.path
end

You can either use

request.original_url 

or

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

to get the current URL.


You can use:

request.full_path

or

request.url

Hopefully it will resolve your problem.

Cheers


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


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

참고URL : https://stackoverflow.com/questions/2165665/how-do-i-get-the-current-absolute-url-in-ruby-on-rails

반응형