1

我无法让嵌套属性使用多态性处理文件上传。这是我的应用程序中的相关源代码。

应用程序/上传器/image_uploader.rb

# encoding: utf-8

class ImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::RMagick
  storage :file

  version :thumb do
    process resize_to_fill: [50, 50]
    process convert: 'jpg'
  end

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end
end

应用程序/模型/photo.rb

class Photo < ActiveRecord::Base
  attr_accessible :image, :imageable_id, :imageable_type
  belongs_to :imageable, polymorphic: true 
  mount_uploader :image, ImageUploader
  validates_presence_of :image, :imageable_id, :imageable_type
end

应用程序/控制器/photos_controller.rb

  class PhotosController < InheritedResources::Base
    def create
      # TODO enforce imageable_id belongs to current account
      @photo = Photo.new(params[:photo])
      if @photo.save
        redirect_to @photo.imageable, notice: 'Photo saved'
      else
        flash[:error] = 'Photo could not be saved'
        redirect_to(:back)
      end
    end
  end

应用程序/模型/listing.rb

class Listing < ActiveRecord::Base
    attr_accessible :photos_attributes
    has_many :photos, :as => :imageable, :dependent => :destroy
    accepts_nested_attributes_for :photos
    mount_uploader :logo, ImageUploader
end

app/views/listings/show.html.haml

%p
  %b Photos:
  %ul.inline
    - @listing.photos.each do |photo| 
      %li= link_to(image_tag(photo.image_url(:thumb)), photo.image_url)

= simple_form_for @listing.photos.new do |f|
  = f.hidden_field :imageable_id
  = f.hidden_field :imageable_type
  = f.input :image, as: :file
  = f.submit 'Upload'

上面的表格有效,但是传递 :imageable_id 和 :imageable_type 对我来说感觉很骇人,并且很容易导致批量分配安全问题。另外,这要求我在 Photo 中有 attr_accessible 以及到 :photos 的 photos_controller.rb 和 RESTful 路由。这一切似乎都非常错误。

这是我的原始形式,感觉更像是 Rails 方式,但它不起作用。似乎多态关联在某种程度上受到干扰。我认为照片属性应该与 params[:listing] 一起发布,而不是单独的 params[:photo]。

app/views/listings/_form.html.haml

= simple_form_for @listing do |f|
  = simple_fields_for :photos, @listing.photos.new do |pf|
    = pf.input :image, :as => :file
  = f.submit 'Upload'

有人可以展示正确的方法吗?

4

0 回答 0