我正在构建一些 Rails 示例应用程序,其中有两个模型“用户”和“项目”。两者之间的关联是用户 has_many 项目。现在的问题是,我愿意为顶部的用户项目提供一些下拉菜单,如果有人点击该下拉菜单,则会将其带到项目显示页面。但是,如果用户位于一个项目的编辑页面并从下拉列表中选择其他项目,我希望他能够到达新选定项目的编辑页面,以显示页面的相同情况。我正在寻找的解决方案是例如:-我们可以使用 params[:controller] 找到当前控制器,使用 params[:action] 找到当前操作,如何找到当前路线。 提前谢谢
如果有人想看看我的代码是什么:- 这是 github 的链接:- 'https://github.com/peeyushsingla/session_test.git/ 这里我使用简单的链接,但实际上我将提供一些将显示的单个下拉菜单,该下拉菜单将适用于所有编辑、显示、新建每个操作
适用于 Rails 4 或最新版
网址示例:
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"
要检索 URL:
# Current URL:
request.original_url
# Current relative URL:
request.request_uri
此外,您还可以通过
current_page
方法查看您是否处于某条路线中。
current_page?(my_path)
# => true / false
对于 Rails 4 使用:
# Current URL:
request.original_url
# Current relative URL:
request.fullpath
您可以使用 url_for
def current_path(params={})
url_for(request.params.merge(params))
end
网址示例
http://localhost:3000/posts
current_path -> /posts
current_path(order: asc) -> /posts/?order=asc