我无法使用多态来获取嵌套属性以处理文件上传。以下是我的应用程序中的相关sourcecde。
应用程序/上传/ 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
应用程序/视图/列表/ 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_controller.rb和RESTful路线。这一切似乎都非常错误。
这是我原来的形式感觉更多的Rails方式,但它没有用。似乎多态关联在某种程度上是干扰。我认为照片属性应该使用params [:listing]而不是单独的params [:photo]。
应用程序/视图/列表/ _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'
有人能说出正确的方法吗?