获取嵌套参数 [英] Get nested params

查看:43
本文介绍了获取嵌套参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有嵌套参数的表单.在以下示例中,如何获取控制器中的amount_whole"值?

I have a form with nested params. In the following example, how do I get the "amount_whole" value in the controller?

    Parameters: {"utf8"=>"✓", "authenticity_token"=>"KCmBI6RLh0LdUsM2r5H1vhNykS1IXecFe5Lct+TuIGc=", "dec_declaration"=>{"declaration_nr"=>"SAL_2012_0001", "dec_declarationlines_attributes"=>{"0"=>{"amount_whole"=>"75"}}

是这样的吗?

amount = params[:dec_declarations][:dec_declarationlines_attributes][:amount_whole]

推荐答案

您忘记了散列中的 "0" 索引.所以你应该能够像这样访问它:

You forgot the "0" index in the hash. So you should be able to access it like this:

amount = params[:dec_declaration][:dec_declarationlines_attributes]["0"][:amount_whole]

params 散列可以使用符号和字符串作为键.

The params hash works with both symbols and strings as keys.

但是,从购买参数的结构来看,您似乎有一个名为 DecDeclaration 的模型,该模型具有该关联的多个 DecDeclarationlines 和 accepts_nested_attributes.所以你应该可以在控制器中像这样使用它:

However, judging buy the structure of the params it looks like you have a model called DecDeclaration which has_many DecDeclarationlines and accepts_nested_attributes for that association. So you should be able to use it like this in the controller:

@dec_declaration = DecDeclaration.build(params[:dec_declaration])
@amount_whole = @dec_declaration.dec_declarationlines.first.amount_whole

因为如果 params 出现在那个结构中,它会自动将嵌套的值分配给关联.

Because if the params comes in that structure, it will automatically assign the nested values to the association.

这篇关于获取嵌套参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆