2013-11-24 45 views
11

我正在构建一些rails示例应用程序,其中我有两个模型用户和项目。两者之间的关联是用户has_many项目。现在的问题是我愿意为用户的项目提供一些下拉菜单,如果有人点击那个项目,它会将其用于项目显示页面。但是,如果用户在一个项目的编辑页面,并从下拉菜单中选择其他项目,我希望他能够到达新选定项目的编辑页面。我正在寻找的解决方案是,例如: - 我们可以使用params [:controller]找到当前控制器,使用params [:action]查找当前操作,我如何找到当前路由。 Thanx提前如何在rails中获取当前路径

如果有人想看到的是我的代码: - 这里是链接github上: - 'https://github.com/peeyushsingla/session_test.git/这里我使用简单的链接,但实际上我将提供一些单一下拉将要显示的将所有的编辑,显示,新的每一个动作

回答

23

工作要检索的URL:

# Current URL: 
request.original_url 

# Current relative URL: 
request.request_uri 

此外,您可以用current_page方法检查您是否是在一定的航线。

current_page?(my_path) 
# => true/false 

对于轨道4使用:

# Current URL: 
request.original_url 

# Current relative URL: 
request.fullpath 
+3

'request.request_uri'不适用于我(Rails 4)我必须用user'path'而不是 – jmarceli

+0

谢谢,我更新了答案 –

+0

undefined方法current_page? –

20

对于轨道4

URL例如: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"

+1

Upvote为实际例子:) –

2

您可以使用url_for

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

URL例如http://localhost:3000/posts

current_path -> /posts

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

相关问题