Reputation: 1051
I have a scenario, In the same form, I have two uploads one is of image type while other one is for doc,excel and PDF etc. I am using gem 'paper-clip' for both. first I want to know how to customize and configure paper clip to upload both types, second I want to restrict both fields not to upload other type. like images fields should not accept other content type similarly vice versa.
Upvotes: 1
Views: 5212
Reputation: 12340
You can check
Paperclip Upload file :-- 1) In Gemfile Include the gem in your Gemfile:
gem "paperclip", "~> 3.0"
If you're still using Rails 2.3.x, you should do this instead:
gem "paperclip", "~> 2.7"
2)In your model
class User < ActiveRecord::Base
attr_accessible :img_avatar, :file_avatar
has_attached_file :img_avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
has_attached_file :file_avatar, :default_url => "/files/:style/missing.doc"
end
3)In your migrations:
class AddAvatarColumnsToUsers < ActiveRecord::Migration
def self.up
add_attachment :users, :img_avatar
add_attachment :users, :file_avatar
end
def self.down
remove_attachment :users, :img_avatar
remove_attachment :users, :file_avatar
end
end
In your edit and new views:
<%= form_for @user, :url => users_path, :html => { :multipart => true } do |form| %>
<%= form.file_field :img_avatar %>
<%= form.file_field :file_avatar %>
<% end %>
In your controller:
def create
@user = User.create( params[:user] )
if ["jpg,"jpeg","gif", "png"].include? File.extname(params[:img_avatar])
@user.img_avatar = params[:img_avatar]
elsif ["doc","docx","pdf","xls","xlsx"].include?File.extname(params[:file_avatar])
@user.file_avatar = params[:file_avatar]
else
flash[:message] = "You are uploading wrong file" #render flash message
end
end
Thanks
Upvotes: 3
Reputation: 71
To expand on the chosen answer (& fix your ArgumentError)..
you can put all the content validations in your model under has_attached_file, like this:
validates_attachment_content_type :img_avatar, :content_type => /^image\/(png|jpeg)/
validates_attachment_content_type :file_avatar, :content_type =>['application/pdf']
this would allow the attachment type for img_avatar to only be png and jpeg (you can add other extensions) and for file_avatar to be, in this case, pdf-only :)
Upvotes: 2