Vue to Rails: 我如何 post 通过强参数创建嵌套对象?

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

给定一个 Rails 后端和一个 Vue 前端,我如何 POST 嵌套 ImageAttachment class?一个Photo可以有一个ImageAttachment。我设置了这些强大的参数,感觉问题就在那里,但我找不到任何东西。

def photo_params
  params.require(:photo).permit(
    image_attachment: %i[data crop_x crop_y crop_width crop_height revert]
  )
end

这是将子 (ImageAttachment) 信息附加到父 Photo 的 Vue 函数。

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

但它的立场给出了这个错误:

ActiveRecord::AssociationTypeMismatch - ImageAttachment(#70277552586900) expected, got {"data"=>#, @original_filename="30594959_1160903097380019_7860735199103942656_o.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"photo[image_attachment][data]\"; filename=\"30594959_1160903097380019_7860735199103942656_o.jpg\"\r\nContent-Type: image/jpeg\r\n">} which is an instance of ActiveSupport::HashWithIndifferentAccess(#70277506611620):

我有 AssociationTypeMismatch。我正在使用 accept_nested_attributes in model。在您的示例中,image_attachment 可能代表关联,这就是错误的原因。 我会使用 attr_accessor : imgattachment 并在控制器中使用这样的东西

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

我的话题:ActiveRecord::AssociationTypeMismatch when trying to register user using devise

似乎是 accept_nested_attributes

的问题

所以解决这个问题的方法是利用 _attributes。 JS:

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

型号:

accepts_nested_attributes_for :image_attachment, allow_destroy: true

控制器:

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