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.
You could do a 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