Carrierwave image upload in nested form still creating record even no file is specified
I have a Carrierwave image upload in a nested simple_form which works (sort of) unless the user does not specify a file, in which case a blank Picture object is created unless there was a previously existing one. Not quite sure how to make it so that if the user doesn't specify a "new" image to upload, the old one isn't deleted and/or a blank record without a file is created.
One (maybe odd) thing I am doing is always sending the logged in @user to the user#edit action, then building a @user.picture if it doesn't exist. I am thinking this is where my bad design is.
# 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
<%= simp开发者_C百科le_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 %>
I think I had the same issue which I solved by adding a reject_if option to the accepts_nested_attribute. So in your example, you could do something like
class User < ActiveRecord::Base
[...]
has_one :picture, :dependent => :destroy
accepts_nested_attributes_for :picture,
:reject_if => lambda { |p| p.image.blank? }
[...]
end
When you use build_* it sets the foreign key on the object. ( similar to saying Picture.new(:user_id => id) )
Try This
# users_controller.rb
def edit
if @user.picture.nil?
@user.picture = Picture.new
end
end
Today I had the same problem, I solved this like:
accepts_nested_attributes_for :photos,
:reject_if => :all_blank
精彩评论