Kyle Lemon
Kyle Lemon

Reputation: 33

Unpermitted parameter in HABTM association

I'm trying to define a has_and_belongs_to_many association between two models in my Rails 5 app (api-only in case that somehow matters). The models are bags and products, and the association works as expected from the console - I can type Bag.last.update(product_ids: [1,2,5]) and creates the associations. However, when trying to send the data through the API controller, I get Unpermitted parameter: :product_ids.

I have read through all of the other answers I can find, and tried to implement those solutions, but I just can't get it to work. Here's the relevant code. Let me know if anything else would be helpful.

bag.rb

class Bag < ApplicationRecord
  has_and_belongs_to_many :products
end
product.rb

class Product < ApplicationRecord
  has_and_belongs_to_many :bags
end
bags_controller.rb

def bag_params
        params.require(:bag).permit(:param1,
                                    :param2,
                                    :param3,
                                    :param4,
                                    product_ids: [])
end

And here's the server output:

Processing by Api::V1::BagsController#update as JSON
  Parameters: {"bag"=>{"product_ids"=>"[1,2]"}, "id"=>"3"}
  User Load (1.7ms)  ...
  Bag Load (1.4ms)  ...
  CACHE User Load (0.2ms)...
  ...
Unpermitted parameter: :product_ids

Can anyone see what I'm doing wrong here? Thanks in advance!

EDIT: I think the problem must be with how the data is being sent, but I still can't figure it out.

Upvotes: 1

Views: 226

Answers (1)

Kyle Lemon
Kyle Lemon

Reputation: 33

Thanks for confirming, Vasilisa! I can't seem to get the front end to send an actual array, so I ended up changing bag_params to this, which works if a simple comma-separated string is sent:

attrs = params.require(:bag).permit(:appointment_id,
                                    :recipient_name,
                                    :package_id,
                                    :price,
                                    :product_ids)

attrs.merge!(product_ids: params[:bag][:product_ids].split(","))
attrs

Upvotes: 1

Related Questions