Any time a project I’m working requires uploading a file I turn to a trusty old friend called attachment_fu. The plugin works great, but lacks the necessary validations. It does have a built-in validates_as_attachment, but only prevents files outside of the set range from being uploaded. What if I wanted to validate the content-type? Well, after doing a little bit of research and digging through the plugin itself I settled on a great validation method. This method can be applied to any one of your upload fields.
1. Pass the allowed content_types
has_attachment :storage => :s3, :content_type => ['audio/mpeg', 'audio/mp3', 'audio/MP3']
2. Place this validate method in your upload model.
def validate
errors.add_to_base("You must upload an mp3 for this song") unless self.filename
unless self.filename == nil
# Songs should only be MP3
[:content_type].each do |attr_name|
enum = attachment_options[attr_name]
unless enum.nil? || enum.include?(send(attr_name))
errors.add_to_base("The file must be an MP3")
end
end
end
end
Hope this helps!
- BROWSE / IN TIMELINE
- « Custom field_error_proc in Ruby on Rails
- » Installing MySql on Mac OS X
- BROWSE / IN Code Ruby on Rails Tutorials
- « Custom field_error_proc in Ruby on Rails
- » Installing MySql on Mac OS X
SPEAK / ADD YOUR COMMENT
Comments are moderated.










