1

我正在嘗試爲使用Carrierwave處理的照片上傳設置多態關聯。我正在使用簡單的窗體來構建我的窗體。我覺得這個關聯是正確的,所以我想知道如果我的問題只是表單或控制器的東西。Rails 3與Carrierwave和簡單表單的多態關聯

這裏是我的協會:

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 

從性能摘錄/ _form.html.erb

<%= f.input :image, :label => 'Image:', :as => :file %> 

這裏是安裝圖像提交時,我得到的錯誤:

undefined method `each' for #<ActionDispatch::Http::UploadedFile:0x00000102291bb8> 

這裏是PARAMS:

{"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"} 

我正在尋找無處不在的幫助多晶ic協會,我無處可去。我已經看到簡單的例子,看起來非常簡單。我注意到的一件事情是,在很多例子中,我的情況下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中不能正常工作:(

回答

3

由於您的模型has_many:圖像(它應該是:圖像,而不是圖像),您需要在視圖中使用nested_forms。您應該建立accepts_nested_attributes_for:對單位和屬性模型圖像,並從改變attr_accessible:圖片:image_attributes

退房http://railscasts.com/episodes/196-nested-model-form-part-1一個很好的指導上得到它會

+0

那完美工作的唯一!我必須做的其他事情是在property.rb中設置attr_accessible:images_attributes。 –