I have a form in a react compnent that includes an image. This component has an associated state for the form, it is quite a large and complex form with many nested arrays of sub elements that vary in length, which is why I do not want to use FormData().
state = {
recipe: {
title: "",
image: null,
ingredient_groups: [
{
title: "",
ingredients: [
{
name: "",
measurement_metric: "",
measurement_imperial: ""
}
]
}
]
}
The state is updated with an onChange handler for the input field like the following
let {recipe} = this.state;
recipe.image = event.target.files[0];
this.setState({recipe});
This is then sent via an axios post request,
let {recipe} = this.state;
axios.post('/api/v1/recipe', {recipe: recipe}).then((result) => {
console.log(result.status)
})
in rails I have a params method set up for the allowed params
def recipe_params
params.require(:recipe).permit(:title,
:image,
{ingredient_groups: [
:id,
:title,
{ingredients: [
:id,
:name,
:measurement_metric,
:measurement_imperial
]}
]})
end
however I am getting nil for recipe_params[:image] when I try to save it into active storage like this:
@recipe.image.attach(recipe_params[:image])
Is what Im doing even possible? Or is the only way to transmit this via a FormData object on the post. I would really prefer this to be done via a pure json method.