R. Elliott Mason wrote:
I am having a weird problem
class Post has_many :uploads end
class Upload belongs_to :post end
In the form in my view the user can upload multiple files at once. In my model there are multiple validations for an Upload, such as being under a certain filesize or not having absurd dimensions if it's an image, etc.
The problem is that if one of the uploads fails validation, the Post object fails validation as well. Previously, I thought I had to specify validates_associated :uploads in the Post model to get this behavior, but seems like that is not the case. If one of the uploads fails I get the error message "Uploads is invalid" in the Post object's errors, which prevents the Post and all other Uploads from saving whether or not they are valid; so basically one bad upload ruins the whole thing. This is kind of bad since it can take a user a while to upload multiple files, and I think it's silly to say "one upload out of ten failed, start all over" when some of the uploads might be good.
What I would -like- to do is accept as many uploads as possible, having the Post object fail to save only if zero uploads were valid. Any invalid uploads get thrown away (although ideally I could somehow keep their errors stored somewhere [in the Post object?] so I can show the user what uploads failed and why).
The file_column plugin, and perhaps other file upload plugins, will automatically store the valid uploads in temporary files so that they do not have to be uploaded again when the form is re-presented.
But if you want the partial save to proceed you'll have to loop through the upload params, creating upload objects, calling valid? on them, and adding them to the post's uploads collection if valid and to a reject array if not, then saving the post (along with the valid uploads) if at least one upload is valid. Re-present the invalid uploads to the user.
If you still need to get rid of the automatic associate validity check that is causing your "Uploads is invalid" message, just add:
class Post validate_associated_records_for_uploads() end end