我正在尝试使用carrierwave
上传图片以保存图片,目前只有保存的参与者才能保存' null'对于相关的行,任何见解都会被批评:
我正在使用rails-api
(https://github.com/rails-api/rails-api)
#controller
def create
@picture = Picture.new(picture_params)
if @picture.save
render json: @picture, status: :created, location: @picture
else
render json: @picture.errors, status: :unprocessable_entity
end
end
class Picture < ActiveRecord::Base
belongs_to :imageable, polymorphic: true
mount_uploader :image_url, ImageUploader
end
class ImageUploader < CarrierWave::Uploader::Base
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end
模式
create_table "pictures", force: true do |t|
t.string "image_url"
t.integer "imageable_id"
t.string "imageable_type"
t.datetime "created_at"
t.datetime "updated_at"
end
控制台输出
Started POST "/pictures" for 127.0.0.1 at 2014-09-01 23:44:47 +0100
Processing by PicturesController#create as */*
Parameters: {"test.jpg"=>#<ActionDispatch::Http::UploadedFile:0x2591868 @tempfile=# <File:C:/Users/xxx/AppData/Local/Temp/RackMultipart20140901-5044-1eui2xj>, @original_filename="test.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"
test.jpg\"; filename=\"test.jpg\"\r\nContent-Type: image/jpeg\r\n">}
←[1m←[36m (0.0ms)←[0m ←[1mbegin transaction←[0m
←[1m←[35mSQL (1.0ms)←[0m INSERT INTO "pictures" ("created_at", "updated_at") VALUES (?, ?) [["created_at", "2014-09-01 22:44:47.289649"], ["updated_at", "2014-09-01 22:44:47.289649"]]
←[1m←[36m (509.0ms)←[0m ←[1mcommit transaction←[0m
Completed 201 Created in 514ms (Views: 2.0ms | ActiveRecord: 510.0ms)
以上POST
不会发送imageable_id或类型,但是在帖子中添加这些属性并不能解决问题。
编辑:将以下内容添加到控制器允许它保存其他字段但载波仍未保存iamge地址
def picture_params
params.require(:picture).permit(:imageable_id, :imageable_type, :image_url)
end
答案 0 :(得分:0)
我解决了这个问题:我使用的是POSTMAN,需要将标题列为picture[image_url]
,而不仅仅是名称。