我有一個載體的圖像上傳在嵌套的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 %>
同樣的效果。創建記錄,設置user_id,圖像爲NULL。 – kokernutz