简体   繁体   English

Ruby on Rails从View上的URL获取参数

[英]Ruby on Rails get paramenter from URL on View

I'd like to get the paramenter from the URL on my view/html. 我想从我的view / html上的URL获取参数。

For example, I'm showing an specific item from my data base, and the URL is like this: " http://localhost:3000/menus/index.%23%3CMenu::ActiveRecord_Relation:0x007f50ed153250%3E?id=6 " 例如,我正在显示数据库中的特定项目,URL如下所示:“ http:// localhost:3000 / menus / index。%23%3CMenu :: ActiveRecord_Relation:0x007f50ed153250%3E?id = 6

What I want is: when I click on the New Button of that specific item, the form opens with the URL " http://localhost:3000/menus/new ", but I want somehow pass that id=6 to this NEW view. 我想要的是:当我单击该特定项目的“新建”按钮时,该表单以URL“ http:// localhost:3000 / menus / new ”打开,但是我想以某种方式将id = 6传递给此新视图。

I am using this code on the html to open the form: <%= link_to 'Novo', new_menu_path %> 我在html上使用以下代码打开表单: <%= link_to 'Novo', new_menu_path %>

I also tried: <%= link_to 'Novo', new_menu_path(@menus, :id) %> , but the id param is always null/empty. 我也尝试过: <%= link_to 'Novo', new_menu_path(@menus, :id) %> ,但是id参数始终为null / empty。

How do I do that? 我怎么做? Thank you 谢谢

To pass an extra param to an url when you define a link_to 在定义link_to时将额外的参数传递给url

<%= link_to 'Novo', new_menu_path(id: @menu.id, other_param: "hello") %>

will generate http://localhost:3000/menus/new?id=6&other_param=hello 将生成http://localhost:3000/menus/new?id=6&other_param=hello

this will add the following to the params hash 这会将以下内容添加到params哈希中

Parameters: {"id"=>"6", "other_param"=>"hello"}

well :id is just a symbol, you need to tell the route helper what to bind to it. :id只是一个符号,您需要告诉路由助手要绑定什么。 For example 例如

<%= link_to 'Novo', new_menu_path(id: params[:id]) %>

which should give you something like /menus/new?id=6 这应该给你类似/menus/new?id=6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM