0

Am I correct in saying that Rails will handle adding associated has_many items to an object if you pass the params in with a definition like tag_ids as an array of ids?

If so, I'm posting the following to my Item controller:-

{
    "title": "Bottle",
    "tag_ids": [25, 26]
}

What's happening is that the tag_ids are being ignored. I already added tag with id 25, but 26 isn't being included.

My controller:-

# PATCH/PUT /api/items/1
  def update
    if @item.update(item_params)
      render json: @item, include: ['tags']
    else
       render json: @item.errors
    end
  end 

  def item_params
    params.require(:item).permit(:name, :tag_ids)
  end

Item has_and_belongs_to_many Tags, and they have a join table of jobs_tags. The association works because I get Tags returned in my response above. I can't seem to add them however. Any idea where I may be going wrong?

Do I need to explicitly add a tag_ids field to the Item model?

s89_
  • 1,533
  • 3
  • 25
  • 40

1 Answers1

2

The tag_ids parameter is an array. But permit(:name, :tag_ids) only permits a single tag_ids attribute.

Change the permission to:

def item_params params.require(:item).permit(:name, tag_ids: []) end

See how to permit an array with strong parameters for more details.

spickermann
  • 100,941
  • 9
  • 101
  • 131
  • Thanks @spickermann - that didn't work for me though, for some reason. When I make the POST - my logs show `Parameters: {"title"=>"Bottle 2", "tag_ids"=>[24, 25], "id"=>"5", "item"=>{"title"=>"Bottle 2"}}` - if that helps? What's the reason for tags not showing in the second part of this? – s89_ Apr 16 '21 at 19:08
  • I no longer get `Unpermitted parameter: :tag_ids`, so that's a step forward - however, the record isn't being updated with the ids. It's still ignoring them. – s89_ Apr 16 '21 at 19:16
  • OK - found the solution. I needed to implement your solution above, AND add `item` as a top level object in my JSON. Not sure why this is required since the other fields update fine without me declaring `item`, but oh well. – s89_ Apr 16 '21 at 19:23