2011-08-17 76 views
2

我有這樣的問題,我的simple_form需要圖像文件上傳字段和圖像url輸入。Rails圖像驗證simple_form

如何進行驗證,以便它可以是圖像文件上傳字段或圖像url,而不是二者都需要。

我在另一個控制器查看:

  <%= f.simple_fields_for :photo_attributes do |d| %> 
<%= d.label :image, :label => 'Upload logo' %> 
<%= d.file_field :image, :label => 'Image' %> 
<%= d.input :image_url, :label => 'Billed URL' %> 
<% end %> 

我的照片模式:

require 'open-uri' 

class Photo < ActiveRecord::Base 
    belongs_to :virksomhed 
    attr_accessor :image_url 

    has_attached_file :image, 
        :url => "/public/images/billeder/photo/:id/:basename.:extension", 
        :path => ":rails_root/public/images/:id/:basename.:extension" 

    before_validation :download_remote_image, :if => :image_url_provided? 

    validates_presence_of :image_remote_url, :if => :image_url_provided?, :message => 'is invalid or inaccessible' 

private 

    def image_url_provided? 
    !self.image_url.blank? 
    end 

    def download_remote_image 
    self.image = do_download_remote_image 
    self.image_remote_url = image_url 
    end 

    def do_download_remote_image 
    io = open(URI.parse(image_url)) 
    def io.original_filename; base_uri.path.split('/').last; end 
    io.original_filename.blank? ? nil : io 
    rescue # catch url errors with validations instead of exceptions (Errno::ENOENT, OpenURI::HTTPError, etc...) 
    end 

end 
+0

你想在模型中驗證這一點,所以當用戶提交表單時,你可以通過錯誤信息回覆他,他不能這樣做,或者你想要這個「活「,使用JavaScript,所以當用戶試圖在選擇了一些圖像後,將網址放入您的表單中,您是否告訴他他應該「決定」? – socjopata 2011-08-17 16:33:24

+0

我想驗證用戶不能同時使用兩個字段,但現在需要1個字段simple_form需要兩個字段 – 2011-08-18 09:12:14

回答

1

如果你談論的是在考慮所要求的標記領域,SimpleForm標記爲所需的每個字段(*)默認。它在自述文件中有這樣的說明,並附有關於如何覆蓋它的示例(required => false)。

在你的模型,我會做這樣的事情:

validate_presence_of :file_field, :unless => :image_url_provided? 
1
validates :image_url, allow_blank: true, format: { 
    with: %r{\.gif|jpg|png}i, 
    message: 'must be a url for gif, jpg, or png image.' 
} 
2

正確的形式是: :用=>%R {(PNG | JPG | JPEG)$}我,

Otherwhise它將允許file.git.something