[Vuejs]-Vue to Rails: how can I post to create a nested object through strong params?

0๐Ÿ‘

โœ…

So the way around this is to leverage the _attributes. JS:

uploading: function (file, xhr, formData) {
  formData.append('photo[image_attachment_attributes][data]', file)
}

Model:

accepts_nested_attributes_for :image_attachment, allow_destroy: true

Controller:

def create
  if @photo.update_attributes!(photo_params)
    response = @photo.reload && @photo.exists? ? @photo.for_vue : nil
    render json: { photo: response }, status: 200
  else
    render json: { error: @photo.errors }, status: 400
  end
end

private

def photo_params
  params.require(:photo).permit(
    image_attachment_attributes:
      %i[data crop_x crop_y crop_width crop_height revert]
  )
end
๐Ÿ‘คt56k

0๐Ÿ‘

I had AssociationTypeMismatch. I was using accept_nested_attributes in model. In your example image_attachment stands for association probably, thats why the error.
I would use attr_accessor : imgattachment and in controller something like this

photo = Photo.new
img_attachment = ImageAttachment.new
img_attachment.data = params[:imgattachment][:data]
photo.image_attachment << img_attachment

My topic: ActiveRecord::AssociationTypeMismatch when trying to register user using devise

Seems its problem with accept_nested_attributes

๐Ÿ‘คsonic

Leave a comment