2

simple_formには画像ファイルのアップロードフィールドと画像のURL入力の両方が必要であるという問題があります。

両方ではなく、画像ファイルアップロードフィールドまたは画像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
4

3 に答える 3

1

ビューでフィールドを必須としてマークすることについて話している場合、SimpleForm はデフォルトで各フィールドを必須 (*) としてマークします。readme にそう書かれており、これをオーバーライドする方法の例を示しています (required => false)。

あなたのモデルでは、次のようなことをします:

validate_presence_of :file_field, :unless => :image_url_provided?
于 2011-09-30T21:25:05.033 に答える
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.'
}
于 2012-07-24T02:36:10.660 に答える