Question

I'm trying to use strong params in Rails 4.1 and failing hard.

# Some request params
params = ActionController::Parameters.new({
  order: {
    shipping_method: '03',
    line_items_attributes: [{
      sale_id: "12847",
      qty: "12"
    }]
  }
})

# try to permit them all
params.permit(:order).permit(
  :shipping_method,
  {
    line_item_attributes: [
      :sale_id,
      :qty,
    ]
  }
)

# Unpermitted parameters: order
# => {}

I expect to be able to permit all those params.

Why am I getting that warning, and why do I get an empty hash as the return value?


It seems require is more helpful, however I still can't get my nested array of hashes

params.require(:order).permit(
  :shipping_method,
  {
    line_item_attributes: [
      :sale_id,
      :qty,
    ]
  }
)

# Unpermitted parameters: line_items_attributes
# => {"shipping_method"=>"03"}
Was it helpful?

Solution

It should be params.require(:order) and not params.permit(:order)

Check this out in Rails Docs : Action Controller Parameters

Your code should look like:

params = ActionController::Parameters.new({
  order: {
    shipping_method: '03',
    line_items_attributes: [{
      sale_id: "12847",
      qty: "12"
    }]
  }
})

and after that

params.require(:order).permit(
  :shipping_method,
  {
    line_items_attributes: [
      :sale_id,
      :qty,
    ]
  }
)

NOTE: You need to permit line_items_attributes (Notice plural items) and NOT line_item_attributes (Not singular item). (Assuming you have 1-M association between Order and LineItem)

OTHER TIPS

Your problem has to do with the fact that you are calling permit twice when defining your accepted parameters. The way the strong parameters work is that you must require the parameter that corresponds to the object you are trying to build (in your case, :order). You can then chain this method with a call to permit, which accepts a comma-separated list of parameters corresponding to the params you wish to accept for your object:

params.require(:order).permit(:shipping_method, :line_items_attributes,...)

If you wish to accept nested params, you must specify them as an array within the permit method:

params.require(:order).permit(:shipping_method, 
                              line_items_attributes: [:sale_id, :qty])

Check out the full documentation for more info.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top