简体   繁体   中英

Trying to save to S3 with Paperclip & Amazon API

Hey guys I've tried looking up the answer to my specific problem and couldn't find a solution. I tried everything. I have a gift model that has paperclip to save an image. The gift instance is populated by an Amazon model ( which grabs information from the amazon api for product details including, image, name and price) but I can't save the image to S3. I think my problem has to do with the fact paperclip is converting it to an amazon S3 link on the "new" route in my gift controller as opposed to when it actually creates the gift. here's some code:

class GiftsController < ApplicationController
  skip_before_action :verify_authenticity_token
  before_action :amazon_url, only: [:new, :new_extension]
  before_action :authenticate_user!

  def new
    @friend = Friend.find_by_id(params[:id])
    if @gift_data.failure == nil
      @gift = Gift.new(
          name: @gift_data.name,
          image: @gift_data.image,
          price: @gift_data.price
      )
    else
      @gift = Gift.new()
      if params[:search]
        @failure = @gift_data.failure
        respond_to do |format|
          format.html
          format.json { render :json => {gift: @gift} }
        end
      end
    end
  end

and my gift model :

class Gift < ActiveRecord::Base
  belongs_to :category
  has_many :ideas
  has_many :friends, :through => :ideas
  # this friends association doesn't work, need to troubleshoot more or figure that out
  # also figure out whether we need it
  has_many :goods


  has_attached_file :image,
                    :storage  => :s3,
                    :styles => { :medium => "370x370", :thumb => "100x100" }
                    validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/

  validates_presence_of :name
  # validates_presence_of :category_id
  # validates :url, :url => {:allow_blank => false}
  # validates :price, presence: true, format: {with: /\A\d+(?:\.\d{0,2})?\z/}, numericality: {greater_than: 0, less_than: 1000000}

end

I've tried adding a method in the gift model to URI.parse the link but it doesn't work. Even tried doing it in the gift controller on the image but that didn't work either. I'm assuming paperclip is processing the image even when it's not yet created and won't even let me create the gift afterwards. Would appreciate some guidance!

Figured it out. Ended up adding an image_url row in table and then making use of URI.parse(image_url) to save it to the image and it saves it to S3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM