AB10
AB10

Reputation: 1021

How to accept/upload audio files in a model as an attachment with Ruby on Rails?

I have created a model called PenUp. My PenUp model has attached files of images and it validates the attachment content type of the image. I now want my model to be able to have audio files attached to it and the audio files content type also.

I'm not sure if I should create a model called Audio for the audio files or should I attach it to the PenUp model just like the image is attached.

I'm using the paperclip gem to attach files. I basically want to be able to upload audio files to my app. I'm not sure what content type's are available to use and how to use it in my PenUp model.

How would I be able to attach audio files and validate the content type?

Here's my model: pen_up.rb

 class PenUp < ActiveRecord::Base
        belongs_to :user
        has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }
        validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
        validates :image, presence: true
      validates :description, presence: true
    end

Thanks in advance!

Upvotes: 0

Views: 951

Answers (1)

Long Nguyen
Long Nguyen

Reputation: 11275

First question: I'm not sure if I should create a model called Audio for the audio files or should I attach it to the PenUp model just like the image is attached.

I think it is depend on your intent, if PenUp should hold an image file and and an audio file, then you should attach audio file to the PenUp model.


Second question: How would I be able to attach audio files and validate the content type?

Here you are:

class PenUp < ActiveRecord::Base
  ...
  has_attached_file :audio
  validates :audio, presence: true
  validates_attachment_content_type :audio, :content_type => [ 'audio/mpeg', 'audio/x-mpeg', 'audio/mp3', 'audio/x-mp3', 'audio/mpeg3', 'audio/x-mpeg3', 'audio/mpg', 'audio/x-mpg', 'audio/x-mpegaudio' ]
end

Base on the format of audio file you want, you can add more or remove content type on content_type array.

Upvotes: 1

Related Questions