开发者

Rails validation of image simple_form

开发者 https://www.devze.com 2023-03-28 12:14 出处:网络
I have that problem that my simple_form require both image file upload field and image url input. How do I validate so that it is either the image fileupload field or the image url that should be re

I have that problem that my simple_form require both image file upload field and image url input.

How do I validate so that it is either the image fileupload field or the image url that should be requried not the both.

My View in another controller:

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

My photo model:

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


The correct form is: :with => %r{.(png|jpg|jpeg)$}i,

Otherwhise it will allow file.git.something


If you're talking about marking fields required in the view, SimpleForm marks each field as required (*) by default. It says so in the readme, complete with an example on how to override this (required => false).

In your model, I would do something like:

validate_presence_of :file_field, :unless => :image_url_provided?


validates :image_url, allow_blank: true, format: {
  with: %r{\.gif|jpg|png}i,
  message: 'must be a url for gif, jpg, or png image.'
}
0

精彩评论

暂无评论...
验证码 换一张
取 消