我正在尝试为使用 Carrierwave 处理的照片上传设置多态关联。我正在使用简单表单来构建我的表单。我觉得关联是正确的,所以我想知道我的问题是否只是表单或控制器的问题。
以下是我的联想:
属性.rb:
class Property < ActiveRecord::Base
attr_accessible :image
...
has_many :image, :as => :attachable
...
end
单位.rb
class Unit < ActiveRecord::Base
attr_accessible :image
...
has_many :image, :as => :attachable
end
图片.rb
class Image < ActiveRecord::Base
belongs_to :attachable, :polymorphic => true
mount_uploader :image, PhotoUploader
end
properties_controller.rb:
def edit
@property = Property.find params[:id]
@property.image.build if @property.image.empty?
end
def update
@property = Property.find params[:id]
if @property.update_attributes params[:property]
redirect_to admin_properties_path, :notice => 'The property has been successfully updated.'
else
render "edit"
end
end
来自属性/_form.html.erb 的片段
<%= f.input :image, :label => 'Image:', :as => :file %>
这是我在提交附加图像时遇到的错误:
undefined method `each' for #<ActionDispatch::Http::UploadedFile:0x00000102291bb8>
这是参数:
{"utf8"=>"✓",
"_method"=>"put",
"authenticity_token"=>"lvB7EMdc7juip3gBZD3XhCLyiv1Vwq/hIFdb6f1MtIA=",
"property"=>{"name"=>"Delaware Woods",
"address"=>"",
"city"=>"",
"state"=>"",
"postal_code"=>"",
"description"=>"2 bedroom with large kitchen. Garage available",
"incentives"=>"",
"active"=>"1",
"feature_ids"=>[""],
"user_ids"=>[""],
"image"=>#<ActionDispatch::Http::UploadedFile:0x00000102291bb8 @original_filename="wallpaper-4331.jpg",
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"property[image]\"; filename=\"wallpaper-4331.jpg\"\r\nContent-Type: image/jpeg\r\n",
@tempfile=#<File:/tmp/RackMultipart20120608-3102-13f3pyv>>},
"commit"=>"Update Property",
"id"=>"18"}
我到处寻找有关多态关联的帮助,但一无所获。我见过看起来很简单的简单例子。我注意到的一件事是,在我的案例中,has_many 关联似乎在很多示例中应该是images
而不是image
。但是,当我这样做时,我得到一个错误:
Can't mass-assign protected attributes: image
正如我在其他博客中看到的那样,我已经尝试更新我的表单以使用 fields_for :
<%= f.input :image, :label => "Photo", :as => :file %>
<% f.simple_fields_for :images do |images_form| %>
<%= images_form.input :id, :as => :hidden %>
<%= images_form.input :attachable_id, :as => :hidden %>
<%= images_form.input :attachable_type, :as => :hidden %>
<%= images_form.input :image, :as => :file %>
<% end %>
我所知道的是我有一段时间让它工作。我对 Rails 很陌生,所以即使调试它也很困难。调试器在 3.2 中不能真正工作并没有帮助 :(