Rails验证图像simple_form

时间:2011-08-17 11:08:23

标签: ruby-on-rails ruby ruby-on-rails-3 simple-form

我遇到的问题是我的simple_form需要图片文件上传字段和图片网址输入。

如何进行验证,使其成为图像文件上载字段或应该要求的图像网址,而不是两者。

我在另一个控制器中的视图:

            <%= 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

3 个答案:

答案 0 :(得分:2)

正确的形式是: :with =&gt; %R {(PNG | JPG | JPEG)$} I,

其他,这将允许file.git.something

答案 1 :(得分:1)

如果您正在讨论在视图中标记所需的字段,SimpleForm默认情况下会将每个字段标记为必需(*)。它在自述文件中这样说,并附有一个如何覆盖它的示例(required =&gt; false)。

在你的模型中,我会做类似的事情:

validate_presence_of :file_field, :unless => :image_url_provided?

答案 2 :(得分: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.'
}