Get nested parameters

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

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

This is true?

amount = params[:dec_declarations][:dec_declarationlines_attributes][:amount_whole]
+3
source share
1 answer

You forgot the "0"hash index . Therefore, you should have access to it as follows:

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

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

Edit

However, judging by the purchase of the parameter structure, it looks like you have a model called DecDeclaration, which has_many DecDeclarationlines and accepts_nested_attributes for this association. Therefore, you should be able to use it in the controller as follows:

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

, , .

+7

All Articles