user5035102
user5035102

Reputation: 33

How to pass array in rails 4 strong parameters

I have to pass a array of food_item_ids in my order_controller. Every order will have many food_items. How can I pass these food_items_id as an array in strong parameters.

orders_controller.rb

def create  
        @order = Order.new(order_params)
        if @order.save
            render :json, @order, status:201, location: [:api, @order]
        else
            render :json, { errors: @order.errors }, status:422
        end
    end

private
  def order_params

    params.require(:order).permit(:customer_id, :order_id, :pos_id, :table_id, :order_number, 
          :order_status,:order_date, :food_item_id => [])
  end
end

Is this the right way to send an array in strong params :food_item_id => []

Upvotes: 2

Views: 191

Answers (2)

gabrielhilal
gabrielhilal

Reputation: 10769

According to the docs https://github.com/rails/strong_parameters#permitted-scalar-values:

The permitted scalar types are String, Symbol, NilClass, Numeric, TrueClass, FalseClass, Date, Time, DateTime, StringIO, IO, ActionDispatch::Http::UploadedFile and Rack::Test::UploadedFile.

To declare that the value in params must be an array of permitted scalar values map the key to an empty array:

params.permit(:id => [])

If it is not working, you might have a misspelling... you have asked how to pass food_items_id, but you are permitting the :food_item_id => []. So, double check the params you are receiving in the controller, you might have to change:

:food_items_id => []

Upvotes: 3

ConnorCMcKee
ConnorCMcKee

Reputation: 1645

The short answer?

Yes, that is how you pass an array to strong parameters.

It is worth noting that if you are passing arrays through strong parameters they must be referenced after all non-array parameters. In this case, however, you are already doing that.

Upvotes: 1

Related Questions