我正在尝试为使用Carrierwave处理的照片上传设置多态关联。我正在使用Simple Form来构建表单。我觉得这种关联是正确的,所以我想知道我的问题是不是表格或控制器的问题。
以下是我的协会:
property.rb:
class Property < ActiveRecord::Base
attr_accessible :image
...
has_many :image, :as => :attachable
...
end
unit.rb
class Unit < ActiveRecord::Base
attr_accessible :image
...
has_many :image, :as => :attachable
end
image.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
来自properties / _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中没有真正起作用是没有用的:(
答案 0 :(得分:3)
由于你的模型has_many:images(应该是:images,not:image),你需要在视图中使用nested_forms。您应该在单位和属性模型上设置accepts_nested_attributes_for:images并将attr_accessible从:image更改为:image_attributes。
查看http://railscasts.com/episodes/196-nested-model-form-part-1以获取有关使用它的良好指南。