5

레일 3 샘플 앱에서 CarrierWave를 사용하고 있습니다.어떻게해야합니까? CarrierWave로 원격 위치 확인이 가능합니까?

class Painting < ActiveRecord::Base 
    attr_accessible :gallery_id, :name, :image, :remote_image_url 
    belongs_to :gallery 
    mount_uploader :image, ImageUploader 

    validates :name,  :presence => true, 
          :length => { :minimum => 5, :maximum => 100 } 
    validates :image,  :presence => true 

end 
: 이것은 내 모델

CarrierWave::DownloadError in ImageController#create 
trying to download a file which is not served over HTTP 

입니다 : 내가 표준 오류 예외가 발생하지 않도록 사용자가 빈 여부 이미지 중 잘못된 URL을 제출하면 원격 위치에 업로드를 확인하려면

이 내 컨트롤러 : 내가 지금 어떤 통찰력이 좋은 것이 문제를 해결하는 방법을 정말 잘 모르겠어요

class PaintingsController < ApplicationController 
    def new 
    @painting = Painting.new(:gallery_id => params[:gallery_id]) 
    end 

    def create 
    @painting = Painting.new(params[:painting]) 
    if @painting.save 
     flash[:notice] = "Successfully created painting." 
     redirect_to @painting.gallery 
    else 
     render :action => 'new' 
    end 
    end 

    def edit 
    @painting = Painting.find(params[:id]) 
    end 

    def update 
    @painting = Painting.find(params[:id]) 
    if @painting.update_attributes(params[:painting]) 
     flash[:notice] = "Successfully updated painting." 
     redirect_to @painting.gallery 
    else 
     render :action => 'edit' 
    end 
    end 

    def destroy 
    @painting = Painting.find(params[:id]) 
    @painting.destroy 
    flash[:notice] = "Successfully destroyed painting." 
    redirect_to @painting.gallery 
    end 
end 

.

+1

나는 약 갈 수있는 가장 좋은 방법은 만드는 것입니다 경우 확실 해요. –

답변

0

이 문제에 대한 해결책이 Github의 CarrierWave Wiki에 추가되었습니다.

편집 : 지금 제안 된 솔루션을 구현하기 위해 노력하고있어하지만 난 그게 작동 얻을 수
. 레일 3.1.3에서 AR을 사용하고 있습니다.

코드를 구현하면 실제로 유효성 검사가 유효합니다. 횡설수설을 업로드하려고하면 좋은 검증 메시지가 나옵니다. 문제는 정상적인 업로드도 방지된다는 것입니다.

+0

이 솔루션은 몽고이족을 위해 일하지 않습니다. mongoid와 함께 작업하는 것이 plase를 점검 할 수 있다면 – hyperrjas

8

동일한 문제가 발생했습니다. 불행히도 이것은 CarrierWave의 디자인 결함 인 것 같습니다 ... 원격 URL의 올바른 유효성 검사를 허용하지 않습니다. CarrierWave는 속성이 설정되면 리소스를 즉시 다운로드하려고 시도하며 URL이 유효하지 않거나 액세스 할 수 없거나 리소스에 예상되는 유형이없는 경우 예외를 throw합니다. 다운로드 유효성 검사가 발생하기 전에 항상 오류 또는 무결성 오류가 발생합니다.

따라서 다른 유효성 검사기를 사용하는 좋은 해결 방법을 찾을 수 없습니다. 내 솔루션은 다음과 같이보고 결국 :

valid = false 
begin 
    par = params[:image].except(:remote_upload_url) 
    @image = Image.new(par) 
    # this may fail: 
    @image.remote_upload_url = params[:image][:remote_upload_url] 
    valid = true 
rescue CarrierWave::DownloadError 
    @image.errors.add(:remote_upload_url, "This url doesn't appear to be valid") 
rescue CarrierWave::IntegrityError 
    @image.errors.add(:remote_upload_url, "This url does not appear to point to a valid image") 
end 

# validate and save if no exceptions were thrown above 
if valid && @image.save 
    redirect_to(images_configure_path) 
else 
render :action => 'new' 
end 

기본적으로, 나는 원격 URL을 제외한 모든 매개 변수를 설정 초기에 구조 블록에서 생성자를 포장합니다. 이를 설정하면 모델에서 오류를 수동으로 설정하여 처리하는 예외가 발생할 수 있습니다. 이 시나리오에서는 다른 유효성 검사가 수행되지 않습니다. 그것은 해킹이지만 나를 위해 일했습니다.

향후 버전에서 모델 유효성 검사 단계 이상이 될 때까지 리소스 다운로드를 지연함으로써이 문제를 해결할 수 있기를 바랍니다.

1

이것은 매우 성가신 문제입니다. 지금은 application_controller.rbrescue_from을 기록했으며 문제를 나타내는 플래시 메시지 만 표시했습니다. 내가 생각할 수있는 최선의 방법입니다. 나는 컨트롤러를 막히는 팬이 아니며 여러 밸리데이션을 필요로하는 모델을 가지고 있다면 그 중복 코드를 사용해야한다.

rescue_from CarrierWave::DownloadError, :with => :carrierwave_download_error 
    rescue_from CarrierWave::IntegrityError, :with => :carrierwave_integrity_error 

    def carrierwave_download_error 
    flash[:error] = "There was an error trying to download that remote file for upload. Please try again or download to your computer first." 
    redirect_to :back 
    end 

    def carrierwave_integrity_error 
    flash[:error] = "There was an error with that remote file for upload. It seems it's not a valid file." 
    redirect_to :back 
    end 
0

CarrierWave 위키의 솔루션이 저에게 효과적이지 않습니다. Peter Hulst가 언급했듯이 CarrierWave는 유효성 검사를하기 전에 파일을로드합니다. 던져 질 때 예외를 캡처하여 나중에 유효성 검사 오류로 다시 추가하는 방법을 발견했습니다. 어떤 이유로 예외가 발생하면 다른 모든 레코드의 속성이 nil이되므로 유효성 검사 전에 캡처하여 다시 추가해야합니다. 이 코드는 모두 모델에 포함됩니다.

그래도 하드 코딩되지 않고 config의 오류 메시지를 사용하려면 약간의 재 작업이 필요합니다.유효성을 검사 : 모델에 remote_image_url과는 URL 및 이미지가 있는지 확인하는 정규식이

attr_accessor :additional_error_message, :original_attributes 

def initialize(*args) 
    self.original_attributes = args[0] 
    begin 
    super 
    rescue CarrierWave::IntegrityError # bad file type 
    self.additional_error_message = 'must be a PNG, JPEG, or GIF file' # depends on your whitelist 
    rescue OpenURI::HTTPError # 404 
    self.additional_error_message = 'could not be found' 
    rescue RuntimeError # redirection 
    self.additional_error_message = 'could not be loaded' 
    rescue CarrierWave::DownloadError 
    self.additional_error_message = 'could not be loaded' 
    rescue 
    self.additional_error_message = 'could not be loaded' 
    end 
end 

before_validation do |image| 
    if additional_error_message.present? 
    errors.add(remote_image_url, additional_error_message) 
    self.name = original_attributes[:name] # replace this with re-adding all of your original attributes other than the remote_image_url 
    end 
end 

# the image will have an "is blank" error, this removes that 
after_validation do |image| 
    errors.delete(:image) if additional_error_message.present? 
end 
관련 문제