回形针:一个模型中有多个“has_attached_file”

时间:2013-02-15 18:06:35

标签: ruby-on-rails database paperclip

我模特的

片段:

attr_accessible :package1_file_name, :package2_file_name
has_attached_file :package1
has_attached_file :package2

来自我的_form(简化版):

<%= form_for(@submission, :html => { :multipart => true, :id => "fileupload"  }) do |f| %>
 <%= f.file_field :package1%>
 <%= f.file_field :package2%>
<% end %>

问题是回形针会为数据库中的每个文件插入两个单独的条目。 但是,我希望它只插入一个条目,因为我的表格中有两个单独的字段:package1_file_namepackage2_file_name

有没有办法实现这个目标?

谢谢!


对于Christian Varga:

也许我不应该简化原始问题中的代码,但在使用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 %>

upload是当前模型的子模型

我不确定multipart是否使两个文件字段的行为类似于单独的附件,但我试图将这两个附件合并为一个。

1 个答案:

答案 0 :(得分:3)

好的,所以我做了一些研究,但仍然无法复制你的问题。我用该代码构建了一个测试应用程序,它只在数据库中插入一个条目。

创建项目(终端)

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

更新型号( submission.rb

attr_accessible :package1, :package2
has_attached_file :package1, :styles => { :medium => "300x300>", :thumb => "100x100>" }
has_attached_file :package2, :styles => { :medium => "300x300>", :thumb => "100x100>" }

更新控制器( submissions_controller.rb

def create
    # @submission = Submission.new(params[:submission])
    @submission = Submission.create(params[:submission])
end

更新表单( _form.html.erb

<%= f.file_field :package1 %>
<%= f.file_field :package2 %>

更新视图( show.html.erb

<%= image_tag @submission.package1.url(:medium) %>
<%= image_tag @submission.package2.url(:medium) %>

运行app&amp;创建新提交

回到控制台:

sqlite3 db/development.sqlite3
select * from submissions;

结果:

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

来自https://github.com/thoughtbot/paperclip#quick-start

的回形针说明