forked from carrierwaveuploader/carrierwave
-
Notifications
You must be signed in to change notification settings - Fork 2
How to: Making uploads work across form redisplays with accept_nested_attributes_for
Simbul edited this page Jun 26, 2012
·
2 revisions
If you have problems with a model with accept_nested_attributes_for, you should check how your parent model deals with validation of its child model. For example, something like this should work (assuming Plant is the parent model and Photo is its child):
class Plant < ActiveRecord::Base
# validations, associations and so on...
has_many :photos
accepts_nested_attributes_for :photo, \
:reject_if => proc {|attributes| attributes['filename'].blank? \
&& attributes['filename_cache'].blank?}
end
class Photo < ActiveRecord::Base
attr_accessible :cover, :title, :filename, :filename_cache
belongs_to :plant
mount_uploader :filename, PhotoUploader
end
If something is still wrong, keep in mind that after a redisplay :filename is empty, while :filename_cache should contain a string value: trying to validate the presence of :filename would cause an error, preventing Rails to save models into your database.