user2453676
user2453676

Reputation: 542

Rails strong params ignoring named param

In config/routes.rb I have the following code

  resources :orders, param: :no do
    resources :order_items, param: :line_item do
      collection do
        get :price
      end
    end
  end

If I post to /orders/6061734/order_items, via json. Then I get the following params:

{"line_item"=>3, "stock_no"=>265062, "order_no"=>"6061734", "order_item"=>{"line_item"=>3, "stock_no"=>265062}}

For parameter whitelisting I have

  def order_item_params
    params.require(:order_item).permit(:order_no, :line_item, ...)
  end

I submitted line_item and stock_no via json parameters and order_no via the url. The order_item param was created by ActionController::ParamsWrapper. The documentation states

On Active Record models with no :include or :exclude option set, it will only wrap the parameters returned by the class method attribute_names.

There is no include or exclude option set on the order_item model, so I am confused as to why order_no is not "wrapped" in the order_item params. Is is because it is part of the url and not part of the json params? I checked OrderItem.attribute_names in the rails console. order_no, line_item and many other attributes are returned.

Upvotes: 0

Views: 650

Answers (1)

Harry Lewis
Harry Lewis

Reputation: 76

I don't think my response requires a full answer, but I don't have enough reputation points to just comment.

Let's take a look at your strong parameter implementation.

params.require(:order_item).permit(:order_no, :line_item, ...)

Using the #require specifies that every attribute you are permitting exist in the :order_item sub-hash. From the parameters you posted, it looks like :order_no lives outside of that sub-hash. In order to get at the :order_no parameter, the following could be used.

params.permit(:order_no)

Upvotes: 1

Related Questions