Search code examples
reactjscarrierwaveform-datastrong-parametersrails-api

Issue sending FormData to Rails API with strong parameters


I want to create a character, with a name and an avatar. Here is my code :

CharacterApi.js, in which I make my network call

function addCharacter(name, avatar) {
  const data = new FormData();
  data.append(‘name’, name);
  data.append(‘avatar’, avatar);

  return authenticatedFetch({
    path: '/teams/characters’,
    method: 'post',
    data
  });
}

characters_controller.rb

def create
  @character = @character.new(character_params)

  if @character.save
    render :show
  else
    render json: @character.errors, status: :unprocessable_entity
  end
end

[. . .]

private

def character_params
  params.fetch(:character, {}).permit(:name, :avatar)
end

Which, when I make my create request, gives me a 422: unprocessable entity error. However, debugs showed me that the right parameters are actually sent, and doing the following makes everything working fine again :

def create
  @character = @characters.new
  @character.name = params[:name]
  @character.avatar = params[:avatar]

[. . .]
end

Even though this second method works, it is not very practical to me, since I’d like to add a few more params in the future.

If I send the params as simple JSON, I can’t get any file (always gives me a null value), but the first method works, this time :

With this I can’t send images or any files, but the initial rails syntax works again

function addCharacter(name, avatar) {
  return authenticatedFetch({
    path: '/teams/characters’,
    method: 'post',
    data: {name, avatar}
  });
}

Is there a reason why the short syntax @character.new(character_params) isn’t working when I send FormData?

I use carrier wave to handle files in rails API. Thanks in advance for any help!


Solution

  • You are using Strong Parameters the wrong way.

    It must be:

    def character_params
      params.require(:character).permit(:name, :avatar)
    end