[英]How can I upload image in S3 by carrierwave and save filename in database?
我嘗試使用載波和霧寶石在s3中上傳照片,但出現錯誤。
undefined method
捕獲nil:NilClass . in line :
. in line :
如果@ premium.save`在控制器/動作中創建
def create
@premium = Article.new(premium_params)
@premium.created_date = Time.now
if @premium.save
redirect_to admincp_premium_path(@premium.id)
else
respond_to do |format|
format.html { render :new }
format.json { render json: @premium.errors, status: :unprocessable_entity }
end
end
結束
這是我的代碼:
carrierwave.rb
CarrierWave.configure do |config|
config.fog_credentials = {
:provider => 'AWS',
:aws_access_key_id => ENV['S3_KEY'],
:aws_secret_access_key => ENV['S3_SECRET'],
:region => ENV['S3_REGION'],
:path_style => true
}
config.cache_dir = "#{Rails.root}/tmp/uploads"
config.fog_directory = ENV['S3_BUCKET']
end
在article_controller.rb中
def create
@premium = Article.new(premium_params)
@premium.created_date = Time.now
if @premium.save
redirect_to admincp_premium_path(@premium.id)
else
respond_to do |format|
format.html { render :new }
format.json { render json: @premium.errors, status: :unprocessable_entity }
end
end
end`在模型artcle.rb中
Class Article < ActiveRecord::Base
...
# set file upload image
mount_uploader :image, ImageUploader
end.
感謝您挽救我的生命:D。
錯誤日志:
Started POST "/admincp/premiums/new" for 127.0.0.1 at 2015-03-30 16:55:53 +0700
Processing by Admincp::PremiumsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"m38F1BDY50lGd/oueT4swpawWueiOBBgOT/MK7xHX4q9aGchBjEc1UnX8UEsTvE+rEz+F3Le9Ru1zVusx7W3dQ==", "premium"=>{"title"=>"rwe", "url"=>"wewe", "start_date"=>"01-03-2015", "end_date"=>"11-03-2015", "image"=>#<ActionDispatch::Http::UploadedFile:0x007fd1b8d97c90 @tempfile=#<Tempfile:/tmp/RackMultipart20150330-11636-1pd05hk.jpg>, @original_filename="canh-dep-tai-nha-trang.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"premium[image]\"; filename=\"canh-dep-tai-nha-trang.jpg\"\r\nContent-Type: image/jpeg\r\n">, "number"=>"10"}, "commit"=>"登録"}
(0.2ms) BEGIN
SQL (0.8ms) INSERT INTO `article` (`title`, `url`, `image`, `start_date`, `end_date`, `number`, `created_date`) VALUES ('rwe', 'wewe', '1d5f0c8e-c41e-4eda-a379-b1b51430372a.jpg', '2015-03-01 00:00:00.000000', '2015-03-11 00:00:00.000000', 10, '2015-03-30 09:55:53.363046')
[fog][WARNING] fog: followed redirect to s3.amazonaws.com, connecting to the matching region will be more performant
(549.1ms) ROLLBACK
Completed 500 Internal Server Error in 7494ms
NoMethodError (undefined method `captures' for nil:NilClass):
app/controllers/admincp/premiums_controller.rb:32:in `create'
我有同樣的問題。 我可以通過在CarrierWave config
調整:region
來解決它。
我為存儲桶使用了S3的US Standard
區域,並設置了region: 'us-east-1'
,這是默認設置。 當我以前在Oregon
設置region: 'us-west-2'
使用存儲桶時region: 'us-west-2'
有效(該選項未在CarrierWave / fog.rb的區域選項中列出)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.