John
John

Reputation: 6612

Get nested params

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"}}

Is it like this?

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

Upvotes: 3

Views: 2244

Answers (1)

DanneManne
DanneManne

Reputation: 21180

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]

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

Edit

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

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

Upvotes: 7

Related Questions