Reputation: 265
I have installed paperclip for my ruby on rails project. But I cant upload multiple images.
I have two different fields where I want to upload images for eg logo and picture.
Can I change the name "avatar" to indicate the name of the field?? Is it possible?
Upvotes: 1
Views: 145
Reputation: 76784
It sounds like you need some ideas to work with Rails
& Paperclip
:
Paperclip
Handles a file attachment & sends the data to your DB
- Creates DB entries:
your_definition_file_name
your_definition_content_type
your_definition_file_size
your_definition_uploaded_at
- Handles Objects called _your_definition
#app/models/attachment.rb
Class Attachment < ActiveRecord::Base
has_attached_file :your_definition
end
Paperclip basically acts like a bridge between your db & your files -- meaning you just have to keep the object name consistent to get it to work
Code
If you have two fields (logo
& picture
), you'll need to declare them in your attachment model, pass their params, and add the columns in your table:
#app/controllers/attachments_controller.rb
def create
@attachment = Attachment.new(attachment_params)
@attachment.save
end
private
def attachment_params
params.require(:attachment).permit(:logo, :picture)
end
#app/models/attachment.rb
Class Attachment < ActiveRecord::Base
has_attached_file :logo
has_attached_file :picture
end
#db/migrate
def change
add_attachment :attachments, :logo
end
attachments
id | logo_file_name | logo_content_type | logo_file_size | logo_uploaded_at | picture_file_name | picture_content_type | picture_file_size | picture_uploaded_at | created_at | updated_at
Recommendation
The above code is not very DRY
I would recommend using a type
attribute in your attachment model, setting the type each time you upload
This way, you can call the attachment
as image
or similar, uploading with the extra para of type
each time:
#app/controllers/attachments_controller.rb
def create
@attachment = Attachment.new(attachment_params)
@attachment.save
end
private
def attachment_params
params.require(:attachment).permit(:image, :type)
end
#app/models/attachment.rb
Class Attachment < ActiveRecord::Base
has_attached_file :image
end
#db/migrate
def change
add_attachment :attachments, :logo
end
attachments
id | image_file_name | image_content_type | image_file_size | image_uploaded_at | type | created_at | updated_at
Upvotes: 0
Reputation: 998
Yes it is possible.
If you want to change "avatar" to "logo" using below command
rails g paperclip modalname logo
where logo is your field name.
I hope you understand and may be it solve your problem.
Upvotes: 1