2011-08-17 77 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