class NewsItem < ActiveRecord::Base
has_many :file_uploads, :as => :uploadable
accepts_nested_attributes_for :file_uploads, :allow_destroy => true
end
class FileUpload < ActiveRecord::Base
belongs_to :uploadable, :polymorphic => true
has_attached_file :upload, :styles => {:thumb => '100x100>'}
end
表單代碼(嵌套NewsItem)
...
<%= f.fields_for :file_uploads do |upload| %>
<div class="file_upload">
<%= upload.file_field :upload %>
</div>
...
<% end %>
...
在提交時我得到以下錯誤:「未知屬性:上傳」。這裏是參數:
{"utf8"=>"✓",
"authenticity_token"=>"MBfxJ4XTizCXv3Mpu971VHCm60bS3Y84Kdxfe+VJD2w=",
"news_item"=>{"title"=>"",
"body"=>"",
"published_date"=>"",
"file_uploads_attributes"=>{"0"=>{"upload"=>#<ActionDispatch::Http::UploadedFile:0x000001070112a8 @original_filename="rails-dd352fc2630e5f9aa5685ef1d7fe5997.png",
@content_type="image/png",
@headers="Content-Disposition: form-data; name=\"news_item[file_uploads_attributes][0][upload]\"; filename=\"rails-dd352fc2630e5f9aa5685ef1d7fe5997.png\"\r\nContent-Type: image/png\r\n",
@tempfile=#<File:/var/folders/hb/2bkct63171lck8d3sg0xfq0c0000gn/T/RackMultipart20111204-3216-71in7a>>,
"name"=>"",
"caption"=>""}}},
"commit"=>"Create News item"}
我使用Rails的3.1.3和回形針「〜> 2.4」。
我想你需要先構建一個file_upload對象,然後才能在nested_form中使用它。另外,也許你需要添加attr_accessible:file_uploads_attributes(不知道多態是如何工作的)。 – yoavmatchulsky