I am creating a React application using Rails API backend.
I have a form component for my Organization model.
I need help properly storing a file/image from my frontend to my backend
Before I began using Active Storage and adding the option to upload images to the form I was able to successfully submit a form for my Organization models. So that leads me to believe this is an isolated incident dealing with Active Storage
- On my backend
I am using Active Storage and have 'has_many_attached :images' for my Organization model
Org Model
class Org < ApplicationRecord
has_many_attached :images
Org Controller
def create
org = Org.create(org_params)
if org.valid?
render json: { org: OrgSerializer.new(org) }, status: :created
else
render json: { error: 'failed to create org' }, status: :not_acceptable
end
byebug
end
(Does not even hit my byebug)
Org Params
def org_params
params.require(:org).permit(..., :images=[])
end
Unsure if the params suppose to be ":images=[]" or "images: []"
Org Serializer
attributes ..., :images
def images
rails_blob_path(object.images, only_path: true) if object.images.attached?
end
- On my frontend I am using a React class form component and storing the information in state
State
state = {
...,
images: [],
Form input
<label><strong>Add Organization Image: </strong></label>
<input
accept="image/*"
multiple={true}
type="file"
name='images'
onChange={this.onFileChange}
/>
Uploading File function
onFileChange = (e) => {
this.setState({
[e.target.name]: e.target.files[0]
})
}
On Form Submit Function
handleOnSubmit = (e) => {
e.preventDefault()
const data = new FormData()
Object.keys(this.state).forEach((key, value) => {
return data.append(key, this.state[key])
})
const reqObj = {
method: 'POST',
headers: {
//Take this out
},
body: data
}
fetch("http://localhost:3001/api/v1/orgs", reqObj)
.then(newOrg => {
this.props.addOrg(newOrg)
this.props.history.push('/organizations')
})
}
As stated before, when I submit this form I do not even hit my byebug so I can inspect, instead I receive the following in my terminal:
Started POST "/api/v1/orgs" for ::1 at 2020-12-31 22:13:57 -0600
Processing by Api::V1::OrgsController#create as */*
Parameters: {..., "images"=>#<ActionDispatch::Http::UploadedFile:0x00007f99f2d66300 @tempfile=#<Tempfile:/var/folders/wq/_w197c7s5ns8wzw8l1wjf_k80000gn/T/RackMultipart20201231-6328-3buku3.jpg>, @original_filename="image3.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name="images"; filename="image3.jpg"
Content-Type: image/jpeg
">,
Completed 400 Bad Request in 0ms (ActiveRecord: 0.0ms | Allocations: 121)
ActionController::ParameterMissing (param is missing or the value is empty: org):
app/controllers/api/v1/orgs_controller.rb:46:in `org_params'
app/controllers/api/v1/orgs_controller.rb:16:in `create'
I would appreciate any input, feedback or assistance...
Thanks!