2011-10-01 20 views
1

我有一個載體的圖像上傳在嵌套的simple_form工作(有點),除非用戶沒有指定一個文件,在這種情況下,一個空白的圖片對象是除非先前存在一個。不太清楚如何製作,以便如果用戶沒有指定要上傳的「新」圖像,則不會刪除舊圖像,也不會創建沒有文件的空白記錄。Carrierwave圖像上傳嵌套形式仍然創建記錄即使沒有指定文件

我正在做的一件事(也許是奇怪的)總是將登錄的@user發送給用戶#編輯動作,然後創建一個@ user.picture(如果它不存在)。我認爲這是我糟糕的設計。

# user.rb 
    class User < ActiveRecord::Base 
    [...] 

     has_one :picture, :dependent => :destroy 
     accepts_nested_attributes_for :picture 

    [...] 
    end 

    # picture.rb 
    class Picture < ActiveRecord::Base 
     attr_accessible :image, :remove_image 
     belongs_to :user 
     mount_uploader :image, ImageUploader 
    end 

    # users_controller.rb 
    def edit 
     if @user.picture.nil? 
     @user.build_picture 
     end 
    end 

    #_form.html.erb 
    <%= simple_form_for @user, :html => {:multipart => true} do |f| %> 
     <%= render "shared/error_messages", :target => @user %> 
     <h2>Picture</h2> 
     <%= f.simple_fields_for :picture do |pic| %> 
     <% if @user.picture.image? %> 
      <%= image_tag @user.picture.image_url(:thumb).to_s %>  
      <%= pic.input :remove_image, :label => "Remove", :as => :boolean %> 
     <% end %> 
     <%= pic.input :image, :as => :file, :label => "Picture" %> 
     <%= pic.input :image_cache, :as => :hidden %> 
     <% end %> 
     <br/> 
    #rest of form here 
    <% end %> 

回答

0

當您使用build_ *時,它會在對象上設置外鍵。 (類似於說Picture.new(:USER_ID => ID))

嘗試這個

# users_controller.rb 
def edit 
    if @user.picture.nil? 
    @user.picture = Picture.new 
    end 
end 
+0

同樣的效果。創建記錄,設置user_id,圖像爲NULL。 – kokernutz

2

我覺得我有我加入了reject_if選項將accepts_nested_attribute解決同樣的問題。因此,在你的榜樣,你可以不喜歡

class User < ActiveRecord::Base 
[...] 

    has_one :picture, :dependent => :destroy 
    accepts_nested_attributes_for :picture, 
    :reject_if => lambda { |p| p.image.blank? } 

[...] 
end 
+0

我應該提到,如果您使用image_cache隱藏字段,請確保您的reject_if語句中不是空白。 –

0

今天我有同樣的問題,我解決了這個名字:

accepts_nested_attributes_for :photos, 
    :reject_if => :all_blank 
相關問題