问题
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 that paperclip will insert two separate entries for each file in the database.
However, I want it to insert into only one entries since I have two separate fields in my table: package1_file_name
, package2_file_name
.
Is there a way to achieve this?
Thank you!
For Christian Varga:
Maybe I shouldn't simplified the code in my original question, but my view actually look like this after using the jQuery file upload
plugin:
<%= 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 a child model of the current model
I am not sure whether the multipart
makes the two file fields act like separate attachment, but I am trying to merge those two attachments into one.
回答1:
Ok, so I've done a bit of research and I'm still unable to replicate your issue. I built a test application with that code, and it only inserts a single entry 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 (submission.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 form (_form.html.erb)
<%= f.file_field :package1 %>
<%= f.file_field :package2 %>
Update view (show.html.erb)
<%= image_tag @submission.package1.url(:medium) %>
<%= image_tag @submission.package2.url(:medium) %>
Run app & create new submission
Go back to 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
来源:https://stackoverflow.com/questions/14900711/paperclip-multiple-has-attached-file-in-one-model