Ruby on rails Rails对图像简单表单的验证

Ruby on rails Rails对图像简单表单的验证,ruby-on-rails,ruby,ruby-on-rails-3,simple-form,Ruby On Rails,Ruby,Ruby On Rails 3,Simple Form,我的简单表单需要图像文件上传字段和图像url输入 如何进行验证,以使图像文件上载字段或图像url都应重新排序,而不是两者都重新排序 我在另一个控制器中的视图: <%= f.simple_fields_for :photo_attributes do |d| %> <%= d.label :image, :label => 'Upload logo' %> <%= d.file_field :image, :label => 'I

我的简单表单需要图像文件上传字段和图像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 %>

'上载徽标'%>
'图像'%>
'计费URL'%>
我的照片模型:

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
需要“打开uri”
类照片“/public/images/biller/photo/:id/:basename.:extension”,
:path=>“:rails\u root/public/images/:id/:basename.:extension”
验证前:下载远程图像,:if=>:图像\u url\u是否提供?
验证是否存在:image\u remote\u url、:if=>:image\u url\u provided?、:message=>“无效或无法访问”
私有的
是否提供def图像_url_?
!self.image\u url.blank?
结束
def下载远程图像
self.image=do\u下载\u远程\u映像
self.image\u remote\u url=image\u url
结束
def do_下载远程图像
io=open(URI.parse(image\uURL))
def io.original_文件名;base_uri.path.split('/').last;结束
io.original_filename.blank?零:io
rescue#使用验证而不是异常捕获url错误(Errno::enoint、OpenURI::HTTPError等)
结束
结束

如果要在视图中标记必填字段,默认情况下,SimpleForm会将每个字段标记为必填(*)。在自述文件中有这样的说明,并附有一个关于如何覆盖它的示例(required=>false)

在您的模型中,我将执行以下操作:

validate_presence_of :file_field, :unless => :image_url_provided?
正确的形式是: :with=>%r{(png | jpg | jpeg)$}i


否则,它将允许file.git.something

您希望在模型中对此进行验证,因此当用户提交您的表单时,您会返回错误消息,告知他不能同时执行这两项操作,或者您希望使用javascript“实时”执行此操作,因此当用户在选择某个图像后尝试将url放入表单时,您会通知他应该“决定”?我想验证用户不能同时使用这两个字段,但现在需要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.'
}