Skip to content

How to: Making uploads work across form redisplays with accept_nested_attributes_for

PirunSeng edited this page Dec 15, 2016 · 3 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 :photos, \
  :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.

Clone this wiki locally