Paperclip: Multiple "has_attached_file" s in one model
snippet from my model:
attr_accessible :package1_file_name, :package2_file_name
has_attached_file :package1
has_attached_file :package2
from my _form (simplified version):
<%= form_for(@submission, :html => { :multipart => true, :id => "fileupload" }) do |f| %>
<%= f.file_field :package1%>
<%= f.file_field :package2%>
<% end %>
The problem is the paperclip inserts two separate records for each file in the database. However, I only want it to be inserted in tags one , since I have two separate fields in my table: package1_file_name
, package2_file_name
.
Is there a way to achieve this?
Thank!
For Christian Varga:
Maybe I shouldn't be simplifying the code in my original question, but my view actually looks like this after using the plugin jQuery file upload
:
<%= f.fields_for :uploads do |upload| %>
<div class="row fileupload-buttonbar">
<!-- The first upload field -->
<span class="btn btn-success fileinput-button">
<%= upload.file_field :package1 %>
</span>
<!-- The second upload field -->
<span class="btn btn-success fileinput-button">
<%= upload.file_field :package2 %>
</span>
</div>
<% end %>
Where upload
is the child model of the current model
I'm not sure what multipart
makes the two file fields act as a separate attachment, but I'm trying to combine the two attachments into one.
source to share
Ok, so I did a little research and I am still unable to replicate your problem. I created a test app with this code and only inserts one record into the database.
Create project (terminal)
rails new paperclip-test
cd paperclip-test
echo "gem 'paperclip'" >> Gemfile
bundle
rails generate scaffold submission
rails generate paperclip submission package1 package2
rake db:migrate
Update model ( submit.rb )
attr_accessible :package1, :package2
has_attached_file :package1, :styles => { :medium => "300x300>", :thumb => "100x100>" }
has_attached_file :package2, :styles => { :medium => "300x300>", :thumb => "100x100>" }
Update controller ( submissions_controller.rb )
def create
# @submission = Submission.new(params[:submission])
@submission = Submission.create(params[:submission])
end
Update the form ( _form.html.erb )
<%= f.file_field :package1 %>
<%= f.file_field :package2 %>
Refresh View ( show.html.erb )
<%= image_tag @submission.package1.url(:medium) %>
<%= image_tag @submission.package2.url(:medium) %>
Run the app and create a new view
Go back to the console:
sqlite3 db/development.sqlite3
select * from submissions;
Result:
1|2013-02-21 21:16:38.898602|2013-02-21 21:16:38.898602|image_1.jpg|image/jpeg|54231|2013-02-21 21:16:38.419947|image_2.jpg|image/jpeg|61766|2013-02-21 21:16:38.658720
Paperclip instructions from https://github.com/thoughtbot/paperclip#quick-start
source to share