2

I'm trying to store and image to a rails 6 API, but when I try to send the image from the front end it creates a new record but it doesn't attach the image to it, saying my parameter is unpermitted. Here is my code:

BACK-END:

class Avatar < ApplicationRecord
  has_one_attached :attachment
end
class AvatarsController < ApplicationController
  def create
    avatar = Avatar.new(avatar_params)

    if avatar.save
      render json: avatar, status: :created
    else
      render json: avatar.errors, status: :unprocessable_entity
    end
  end

  private

  def avatar_params
    params.require(:avatar).permit(:attachment)
  end
end

FRONT-END:

import React from 'react';
import axios from 'axios';

const Avatar = () => {
  const handleChange = event => {
    const attachment = new FormData();
    attachment.append('avatar[attachment]', event.target.files[0]);
    axios.post('/api/v1/avatars', { avatar: { attachment } }, { withCredentials: true });
  };

  return (
    <form>
      <input type="file" accept="image/*" onChange={handleChange} />
    </form>
  );
};

export default Avatar;

But when I try to submit it I get this:

Parameters: {"avatar"=>{"attachment"=>{}}}

Unpermitted parameter: :attachment

However the transaction begins and commits successfully, without making the attachment

Here is a very a very similar question, but that solution didn't work for me either.

I anyone have any idea on how to solve this, I would really appreciate the help.

0 Answers0