Ruby-on-rails 访问 POST 参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/708035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:05:54  来源:igfitidea点击:

accessing POST parameters

ruby-on-rails

提问by brodie31k

When I add a new "product" using my scaffold create rails app, the following line properly adds a new product

当我使用脚手架创建 rails 应用程序添加新的“产品”时,以下行正确添加了一个新产品

@product = Product.new(params[:product])

When I try to add a new product using the following URL (trying to POST data up from a java program).

当我尝试使用以下 URL 添加新产品时(尝试从 Java 程序 POST 数据)。

http://localhost:3000/products?serial=555&value=111

The product is not created, however I can access the "serial" and "value" values like this:

未创建产品,但是我可以像这样访问“序列”和“值”值:

 @product = Product.new
 @product.serial=params[:serial]
 @product.value=params[:value]
 @product.save

To further confuse me, if I use the rails app to add a new product, the params[:serial]and params[:value]variables are empty.

更让我困惑的是,如果我使用 rails 应用程序添加新产品,则params[:serial]params[:value]变量为空。

Can someone please point me in the right direction.

有人可以指出我正确的方向。

Thanks

谢谢

回答by Gdeglin

The Model.new method takes a hash.

Model.new 方法采用散列。

params[:product]actually contains something like {:serial => 555, :value => 111}

params[:product]实际上包含类似的东西 {:serial => 555, :value => 111}

The url you would want to use is:

您要使用的网址是:

http://localhost:3000/products?product[serial]=555&product[value]=111

(Make sure that you are indeed using POST)

(确保您确实在使用 POST)

If you want to keep your current url scheme you would have to use:

如果要保留当前的 ​​url 方案,则必须使用:

@product = Product.new({:serial => params[:serial], :value => params[:value]})

You can also determine exactly what is available inside of params by printing it out to console using:

您还可以通过使用以下命令将其打印到控制台来准确确定 params 中可用的内容:

p params

Good luck!

祝你好运!