Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to permit arrays with hash in Rails 4?

There is the following params in Rails 4:

{"delivery_time":"10","delivery_type_id":"1","order_items":[{"count":"5","item_id":"1"}],"order_status_id":"1","user_id":"1","action":"create","controller":"api/v1/orders"}

There is the following strong params:

params.permit(:user_id, :order_status_id, :delivery_type_id, :delivery_time, order_items:[])

But this code returns hash without 'order_items' array. I think the reason is hash in array. Please, tell me, how can I fix it? Thanks in advance

like image 683
malcoauri Avatar asked Dec 27 '13 07:12

malcoauri


2 Answers

You can include nesting arrays, for your example it would be:

params.permit(:user_id, :order_status_id, :delivery_type_id, :delivery_time, order_items: [:count, :item_id])

Others can find out more here - http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html

like image 146
veritas1 Avatar answered Sep 27 '22 21:09

veritas1


As described here, you can permit the nested attributes as below.

params.permit(:user_id, :order_status_id, :delivery_type_id, :delivery_time, order_items_attributes:[:count, :item_id])

However, remember to add following line to accept nested attribute in model. For example:

class Order < ActiveRecord::Base
  has_many :order_items
  accepts_nested_attributes_for :order_items
end
like image 36
sunil Avatar answered Sep 27 '22 22:09

sunil