简体   繁体   English

在Rails中访问表单参数

[英]Getting access to the form params in Rails

I have a form with hidden field: 我有一个带有隐藏字段的表单:

 <%= f.hidden_field(:equipment_id, :value => " ") %> 

The value for this field is submitted via js. 该字段的值是通过js提交的。 So that my generated html looks like this: 这样我生成的html看起来像这样:

 <input value="2" type="hidden" name="programm[equipment_id]" id="programm_equipment_id"> 

When i submit my form my parameters look like this: 当我提交表单时,我的参数如下所示:

 "programm"=>{ .. some other params .., "equipment_id"=>"2" } 

In my controller's create method I try to assign equipment_id parameter to @programm.equipment_id: 在控制器的创建方法中,我尝试将equipment_id参数分配给@ programm.equipment_id:

 @programm.equipment_id = params[:programm => :equipment_id ] 

like that. 像那样。 Where equipment_id is an integer column in database. 其中equipment_id是数据库中的整数列。 The problem is that nothing gets assigned. 问题是什么都没有分配。 If i try to cast .to_i "0" is being assigned and stored in database. 如果我尝试强制转换.to_i,则“ 0”被分配并存储在数据库中。 I also tried to do: 我也尝试做:

 @programm.equipment_id = params[:equipment_id ] 

But the problem is the same. 但是问题是一样的。

The params are nested. 参数是嵌套的。 You can access it like this: 您可以像这样访问它:

@programm.equipment_id = params[:programm][:equipment_id]

这应该可以解决问题:

@programm.equipment_id = params[:programm][:equipment_id]

for the view like this:- 对于这样的视图:

<%= form_for(@programm) do |f|%>
  <%= f.hidden_field(:equipment_id, :value => " ") %>
<%end%>

Upon form submission the value entered by the user will be stored in params[:programm][:equipment_id] and can be used to access the value. 提交表单后,用户输入的值将存储在params[:programm][:equipment_id] ,并可用于访问该值。

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

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