使用cancancan gem后无法保存带有图像的对象

时间:2019-02-19 20:28:34

标签: ruby-on-rails ruby ruby-on-rails-5 cancancan

我能够用图像保存对象。但是在整合cancancan gem之后,无法保存它:

  

EventsController#new访问被拒绝的AWS :: S3 ::错误:: AccessDenied

image = event_params[:cover_image]

  if image.present?
    raise "Unacceptable file format" if !image.content_type.include?("image/")

    original_filename =  image.original_filename
    photo_extname = File.extname(original_filename).downcase
    raise "Please upload images with .jpg or .png format."  unless [".jpg", ".jpeg", ".png"].include?(photo_extname)
  end


  event = Event.new(event_params.except(:client))
  event.event_wf_balance_payment_enabled = session[:event_preflight]['event_wf_balance_payment_enabled'].present?
  event.video_wf_asset_request_enabled = session[:event_preflight]['video_wf_asset_request_enabled'].present?

  # error is here,cannot save
  event.save

  event.vg_enable_video_workflow if session[:event_preflight]['video_wf_state_enabled'].present?
  event.vg_enable_photo_workflow if session[:event_preflight]['photo_wf_state_enabled'].present?

  if image.present?
    safe_name = SafeName.prepare(image.original_filename)
    event.cover_image_file_name = image.original_filename
    event.cover_image_content_type = image.content_type
    event.cover_image_file_size = image.size
    event.cover_image_status = Event::COVER_IMAGE_STATUSES[:upload_success]
    event.save
    photo_extname_lowercase = photo_extname.downcase

    credentials = Aws::Credentials.new(Rails.application.secrets.aws['aws_access_key_id'], Rails.application.secrets.aws['aws_secret_access_key'])
    aws_s3_resource = Aws::S3::Resource.new(region: Rails.application.secrets.aws['aws_region'], credentials: credentials)
    bucket = aws_s3_resource.bucket(Rails.application.secrets.aws['aws_s3_assets_bucket'])
    cover_photos_dir = Rails.application.secrets.aws['aws_s3_event_cover_photos_dir']
    id_hash = Digest::MD5.hexdigest(event.id.to_s)
    unique_filename = "#{id_hash}-#{safe_name}_original#{photo_extname_lowercase}"
    key = "#{cover_photos_dir}/#{event.id}/#{unique_filename}"
    object = bucket.object(key)
    object.put(body: image)
  end

有人知道为什么我会得到这种错误吗?我尝试调试,但我只能收到无法保存事件对象的信息,但是当我发送没有图像的数据时,一切正常。

0 个答案:

没有答案