How to get the current route in rails

青春壹個敷衍的年華 提交于 2019-12-03 19:28:53

问题


I am building some rails sample application in which I am having two models User and Projects. Association between both is user has_many projects. Now the question is I am willing to provide some drop down for user's projects on top and if some one click on that one it will take that to project show page. But if user is at edit page of one project and select other project from dropdown I want him to reach edit page of new selected project same case for show page any idea. The solution I am looking for is e.g:- we can find current controller using params[:controller], find current action using params[:action] how can I find current route. Thanx in advance

If someone want to see what is my code:- here is the link for github:- 'https://github.com/peeyushsingla/session_test.git/ Here I am using simple link but actually I will provide some single drop down that will be displayed that will work for all the edit, show, new every action


回答1:


To retrieve the URLs:

# Current URL:
request.original_url

# Current relative URL:
request.request_uri

Additionally, you can check with the current_page method whether you are in a certain route.

current_page?(my_path)
# => true / false

For Rails 4 use:

# Current URL:
request.original_url

# Current relative URL:
request.fullpath



回答2:


For Rails 4

URL example: http://localhost:3000/allreferred?&referred_name=maria

request.path -> "/allreferred"

request.base_url -> "http://localhost:3000"

request.fullpath -> "/allreferred?&referred_name=maria"

request.original_url -> "http://localhost:3000/allreferred?&referred_name=maria"




回答3:


You can use url_for

def current_path(params={})
  url_for(request.params.merge(params))
end

URL example http://localhost:3000/posts

current_path -> /posts

current_path(order: asc) -> /posts/?order=asc



来源:https://stackoverflow.com/questions/20181216/how-to-get-the-current-route-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!