这只是一个好奇的问题。
Rails是神奇的,因为它为我们做了很多事情,但它伴随着知识的诅咒。当Rails接收到http请求时,我们可以通过params[]访问来自客户端的输入。但是,我注意到params可以同时接受来自url_params和form_data的输入。例如:
# Get users/:id (param comes from url)
# Post users (param comes from form)params[]的工作方式有什么规则吗?Rails会把所有参数从url和form放到params[]吗?
在NodeJS的例子中,有一个区别
request.params
request.body
request.query发布于 2014-07-17 09:18:36
什么是params?
params不过是从浏览器发送http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods时发送给控制器的参数。
类型的params?
如果你看看rail guides,上面写着
There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, called query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from an HTML form which has been filled in by the user
有关于params如何工作的规则吗?
正如@zwippie所指出的,rails并不区分您的params是来自表单还是来自查询字符串,但是它们在rails将这些参数放入散列中的方式不同,因此在控制器中访问它们的方式也不同。
查询字符串的:
如果你的网址是:
http://www.example.com/?vote[item_id]=1&vote[user_id]=2那么你的护身符看起来会是:
{"item_id" => "1", "user_id" => "2"}因此您可以通过params[:item_id] and params[:user_id]在控制器中访问它们。
用于发布数据或来自表单的:
让我们说你的表格就像
<%= form_for @person do |f| %>
<%= f.label :first_name %>:
<%= f.text_field :first_name %><br />
<%= f.label :last_name %>:
<%= f.text_field :last_name %><br />
<%= f.submit %>
<% end %>当您提交表单时,参数将如下所示
{"person"=> {"first_name"=>"xyz", "last_name"=>"abc"}}注意表单是如何将参数嵌套在散列中的,因此要在控制器中访问参数,您必须执行params[:person]操作,并获得可以执行params[:person][:first_name]的单个值。
https://stackoverflow.com/questions/24795720
复制相似问题