Ruby-on-rails 从表单参数中获取数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5258384/
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
Get data from form params
提问by Maki
I'm new for rails and ruby. I try to make a simple project and have this problem. I have a view with some text fields on it, when I press submit button, in my controller I need the values from this fields as strings, I try this way params[:field1], but the value is in this format {"field1"=>"some_value"}, it's not a string and I have the problems with it. How can I solve it?
我是导轨和红宝石的新手。我尝试做一个简单的项目并遇到这个问题。我有一个带有一些文本字段的视图,当我按下提交按钮时,在我的控制器中,我需要这些字段中的值作为字符串,我尝试这种方式params[:field1],但值采用这种格式 {"field1"=>"some_value "},它不是字符串,我遇到了问题。我该如何解决?
UP: view code
UP:查看代码
<%= form_tag :action=>:login_user do %>
<div class="field">
<h2>Login</h2>
<%= text_field "field1", "field1" %>
</div>
<div class="field">
<h2>Password</h2>
<%= password_field "field2", "field2" %>
</div>
<div class="actions">
<%= submit_tag "Login" %>
</div>
<% end %>
回答by fl00r
params[:field1]
is correct way.
是正确的方法。
Your params is a hash:
你的参数是一个散列:
params => {"field1"=>"some_value"}
so to get field1you should call params[:field1]
所以为了让field1你应该打电话params[:field1]
UPD
UPD
For your structure (that is actaully bad) you should call for params this way:
对于您的结构(实际上很糟糕),您应该以这种方式调用参数:
params[:field1][:field1]
params[:field2][:field2]
better to use text_field_tagand password_field_tagin your case:
更好地使用text_field_tag,password_field_tag在您的情况下:
<%= text_field_tag :field1 %>
<%= password_field_tag :field2 %>
回答by Ashish
Try to use like this:
尝试像这样使用:
<%= text_field_tag "field1" %>
<%= password_field_tag "field2" %>
回答by rubyprince
Using the code you have pasted you will have to access it as params[:field1][:field1]and params[:field2][:field2]. So as Ashish suggested you should use text_field_tag. Or in the conventional way of Rails, use form_forto bind both the fields to a single key and use update_attributesor create.
使用您粘贴的代码,您必须以params[:field1][:field1]和访问它params[:field2][:field2]。所以正如 Ashish 建议你应该使用 text_field_tag。或者在 Rails 的传统方式中,使用form_for将两个字段绑定到单个键并使用update_attributesor create。

