kostasew
kostasew

Reputation: 93

how do i get params as array in ruby on rails?

i have the following in my controller

    def invoice_params
      params.require(:invoice).permit({items: [:items]}, :price, :tax, :discount, :sum)
    end

and in my _form

<td><input  size="8" <% form.text_field :items  %> /></td> [pants]
<td><input  size="8" <%= form.text_field :items %> /></td> [spoon]
<td><input  size="8" <%= form.text_field :items %>/></td>  [nil]
<td><input  size="8" <%= form.text_field :items  %> /></td> [nil]
<td><input  size="8"  /></td>

so i want my array be like ["pants","Spoon",nil,nil]

with that style i have the following error in my server

Started POST "/invoices" for 10.0.2.1 at 2020-04-09 00:46:55 +0000
Cannot render console from 10.0.2.1! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by InvoicesController#create as HTML
  Parameters: {"authenticity_token"=>"94T3Stght1p9n9Bo44+lvS7CMnE5PEkuic5DP8ifYH4yxY5roVt19ZHpL6sIaiO31i/S5DADP+/ffNG3wdobLQ==", "invoice"=>{"items"=>"das", "tax"=>""}, "commit"=>"Create Invoice"}
**Unpermitted parameter: :items**

Upvotes: 1

Views: 191

Answers (1)

Thang
Thang

Reputation: 841

<input type="text" name="invoice[items][]" value="pants">
<input type="text" name="invoice[items][]" value="spoon">

Will give you the params as an ARRAY: { invoice: { items: ["pant", "spoon"] } }

<input type="text" name="invoice[items][1]" value="pants">
<input type="text" name="invoice[items][2]" value="spoon">

Will give you the params as a HASH: { invoice: { items: { "1": "pant", "2": "spoon" } } }

For your problem, you need to specify the name manually like below:

<td><%= form.text_field name: "invoice[items][]" %> /></td>
<td><%= form.text_field name: "invoice[items][]" %> /></td>
<td><%= form.text_field name: "invoice[items][]" %> /></td>
<td><%= form.text_field name: "invoice[items][]" %> /></td>

Upvotes: 3

Related Questions