我无法使用Rails 5 API和carrierwave-base64将图像保存到数据库中。我已经阅读了堆栈和文档,无法找到解决方案。我将图像作为base64字符串从angular传递给Rails API。图像肯定是编码的,因为我从终端的角度和轨道获得控制台日志。图像将保存为字符串,位于“媒体表中的图像”列中。
但是,当我点击“保存”时,rails会返回404,并显示消息:
ActiveRecord :: RecordNotFound(找不到'id'= =的媒体):
任何帮助都会非常感激,因为我完全难过。提前致谢。代码:
image_uploader.rb:
class ImageUploader < CarrierWave::Uploader::Base
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
def extension_whitelist
%w(jpg jpeg gif png)
end
end
media_controller.rb
class MediaController < ApplicationController
before_action :set_medium, only: [:show, :create, :update, :destroy]
# skip_before_action :authenticate_user!
# GET /media
def index
@media = Medium.all
render json: @media
end
# GET /media/1
def show
render json: @medium
end
# POST /media
def create
# @medium = Medium.new(Uploader.upload(medium_params))
if @medium.save
render json: @medium, status: :created, location: @medium
else
render json: @medium.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /media/1
def update
if @medium.update(medium_params)
render json: @medium
else
render json: @medium.errors, status: :unprocessable_entity
end
end
# DELETE /media/1
def destroy
@medium.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_medium
@medium = Medium.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def medium_params
params.require(:medium).permit(:title, :body, :image)
end
end
模型/ medium.rb:
class Medium < ApplicationRecord
has_and_belongs_to_many :projects, class_name: "Project", join_table:
"media_projects"
has_and_belongs_to_many :pages, class_name: "Page", join_table:
"media_pages"
mount_base64_uploader :image, ImageUploader
end
串行器/ medium_serializer.rb:
class MediumSerializer < ActiveModel::Serializer
attributes :id, :title, :body, :image
has_many :projects
has_many :pages
end
感谢您的帮助!抱歉华夫饼,我是新手,这是我的第一篇文章。
我通过从用户模型中的before_action中删除:create然后编辑create函数来修复此问题,如下所示:
def create
uploader = ImageUploader.new
@medium = Medium.new((medium_params))
if @medium.save
uploader.store!(@medium)
render json: @medium, status: :created, location: @medium
else
render json: @medium.errors, status: :unprocessable_entity
end
end
欢呼声
答案 0 :(得分:0)
从:create
before_action :set_medium