Rails回形针文件上传字段无法正常工作 - 多选图片上传

时间:2011-11-07 07:42:02

标签: ruby-on-rails ruby ruby-on-rails-3 paperclip

我在使用文件上传字段上传图片时遇到了一些问题。它不上传任何东西。但是图片网址字段有效。我认为这与我的模型有关。

我的表格:

<%= simple_form_for [:admin, @virksomhed] do |f| %>
    <%= f.simple_fields_for :link_attributes do |d| %>
    <% end %>
<%= f.simple_fields_for :photo_attributes do |d| %>
    <%= d.label :image, :label => 'Upload logo', :required => false  %>
    <%= d.file_field :image, :label => 'Image, :required => false', :style => 'margin-bottom:2px'  %>
    <%= d.input :image_url, :label => 'Billed URL', :required => false %>
<% end %>
<%= f.submit "Opret virksomhed" %>
<% 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?


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

我的狐狸模特:

class Virksomhed < ActiveRecord::Base
has_one :photo

accepts_nested_attributes_for :photo
end

2 个答案:

答案 0 :(得分:0)

尽管在后台使用了photo_attributes,但我能找到的所有示例似乎都暗示你应该使用它:

<%= f.simple_fields_for :photo do |d| %>

答案 1 :(得分:0)

<%= f.simple_fields_for :photo_attributes, :html => { :multipart => true } do |d| %>

我的表格也添加了, :html => { :multipart => true }

它解决了这个问题。