[英]How to pass and receive parameters in url in Ruby on Rails?
I am new to ruby, i would like to pass parameters in the url and receive it in controller. 我是红宝石的新手,我想在url中传递参数并在控制器中接收它。
I am expecting operation like 我期望像
www.mysite.com/getuser/id/22
where getuser is the param name and 22 is its value. 其中,getuser是参数名称,22是其值。
Please provide me if there is any useful links that i can refer to. 如果有任何有用的链接可供参考,请提供给我。
Thanks in advance 提前致谢
Please read everything in the Rails Guide to Routing . 请阅读《 Rails路由指南》中的所有内容。 There are two main cases there: 那里有两种主要情况:
RESTful routes: only use GET, PUT, POST, DELETE. RESTful路由:仅使用GET,PUT,POST,DELETE。 Rails maps that by using the method resources
. Rails通过使用方法resources
映射。 resources :pages
will lead to the following routes (and URLs) automatically: resources :pages
将自动导致以下路由(和URL):
sites GET /sites(.:format) {:action=>"index", :controller=>"sites"} POST /sites(.:format) {:action=>"create", :controller=>"sites"} new_site GET /sites/new(.:format) {:action=>"new", :controller=>"sites"} edit_site GET /sites/:id/edit(.:format) {:action=>"edit", :controller=>"sites"} site GET /sites/:id(.:format) {:action=>"show", :controller=>"sites"} PUT /sites/:id(.:format) {:action=>"update", :controller=>"sites"} DELETE /sites/:id(.:format) {:action=>"destroy", :controller=>"sites"}
Other routes: There is a rich set of methods you can use in your routes file to add additional routes. 其他路线:您可以在路线文件中使用多种方法来添加其他路线。 But keep in mind: If you just want to address a resource, it is better to stick to restful routes. 但请记住:如果您只想寻址资源,最好坚持使用宁静的路线。 A typical example is_ match ':controller(/:action(/:id))'
. 一个典型的例子是_ match ':controller(/:action(/:id))'
。 This allows URLs like: 这样可以使用以下网址:
localhost:3000/sites/help
: controller == SitesController
, action == help
localhost:3000/sites/help
:控制器== SitesController
,操作== help
localhost:3000/sites/search/something
: controller == SitesController
, action == search
, parameter in params
is something
under the key id
. localhost:3000/sites/search/something
:控制器== SitesController
,行动== search
,在参数params
是something
下键id
。 So inside the action search
, you will find params[:id]
bound to "something"
. 因此,在动作search
,您会发现绑定到"something"
params[:id]
。 In your config/routes.rb file you write: 在config / routes.rb文件中,您可以编写:
resources :users
Then you create the controller: 然后创建控制器:
rails g controller users
Inside your controller file you have something(contrived) there like : 在控制器文件中,您有一些(人为的)内容,例如:
def show
my_id_param = params[:id]
end
When you go to: www.mysite.com/user/22 当您访问:www.mysite.com/user/22
my_id_param will be 22 my_id_param将为22
I think rails guides are quite good resource, just google for them, has ton of good info there. 我认为Rails指南是相当不错的资源,只是Google为其提供了很多有用的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.