Home > OS >  Rails not updating record when passed an array of association ids
Rails not updating record when passed an array of association ids

Time:09-17

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?

CodePudding user response:

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.

  • Related