Se guardan varios archivos adjuntos de clip sin especificar una entrada de archivo

I have a User model which has a has_many association of Asset model(standard paperclip setup). In the view, I use fields_for helper to setup a number of file fields for the assets. When the end user does not specify a file, the asset records will not be saved. Which is what I want. So far so good.

Then I added a caption attribute to Asset model. I also put a text field to each corresponding file field. Here comes the problem. When the end user does not specify a file or a caption, the asset records will be SAVED. The saved record has a caption of empty string, with all other paperclip attributs being nil.

The question is how can I prevent the asset record being saved when there is no file assigned to paperclip attributes? And since the assets are optional, I don't want any error feedback generated. Any ideas? Thanks.

preguntado el 26 de agosto de 12 a las 03:08

1 Respuestas

Podrías hacer un validates_presence_of :caption in your Asset model, but that also makes captions required. How about this checking for the presence of a file on all assets linked to the User before_validation? Something like this maybe? (might need some tweaking)

class User < AR::Base
  has_many :assets, :dependent => :destroy

  before_validation :check_assets

  def check_assets
    self.assets.each do |asset|
      unless asset.attachment.file?
        if asset.new_record?
          self.assets.delete(asset)
        else
          asset.destroy
        end
      end
    end
  end
end

Respondido 26 ago 12, 21:08

Great idea! That will do exactly what I want! Thanks very much! One tweaking would be iterating a copy of assets so that assets.delete(asset) behaves good. - Ziyu

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.