使用Paperclip在ror中多次上传

时间:2013-02-14 17:00:19

标签: jquery ruby-on-rails paperclip photos

我正在使用回形针为一栋建筑上传一张照片。 http://www.youtube.com/watch?v=KGmsaXhIdjc我用这种方式做到了。但我知道我决定将很多照片上传到一栋楼。我可以用回形针做到这一点,还是必须改变它并使用jQuery?如果我可以怎么样? Ps:如果需要,我会上传我的代码。 ps:我想在photo2和photo 3的数据库中再制作2个列 ..顺便说一句,我看到所有人都生成资产来做到这一点。我认为我用不同的方式上传1张照片。这意味着我必须改变一切吗?

更新1:

在routes.rb

resources :buildings do 
      resources :photos
  end

in buldings> _form

<%= form_for(@building, :html=>{:multipart => true}) do |f| %>
  <% if @building.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@building.errors.count, "error") %> prohibited this building from being saved:</h2>

      <ul>
      <% @building.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :status %><br />
    <%= f.select :status, Building::STATUS, :prompt=>'Select status of the building' %>
  </div>
  <div class="field">
    <%= f.label :description %><br />
    <%= f.text_area :description, :rows => 10 %>
  </div>
  <div class="field">
    <%= f.label :price %><br />
    <%= f.text_field :price %>
  </div>
  <div class="field">
    <!--<%= f.label :photo %><br />
    <%= f.file_field :photo %> -->
    <%= f.fields_for :photos do |photo| %>  
    <% if photo.object.new_record? %>
      <%= photo.file_field(:image) %>

     <% else %> 
        <%= image_tag(photo.url(:thumb)) %>
        <%= photo.hidden_field :_destroy %>
        <%= photo.link_to_remove "X"%>
    <% end %>
  <% end %>

    <p><%= f.link_to_add "Add photo", :photos %></p>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

在模型&gt;建筑

 attr_accessible :description, :price, :status, :title, :photo

accepts_nested_attributes_for :photo, :allow_destroy => true

  has_attached_file :photo ,
                  :url  => "/assets/products/:id/:style/:basename.:extension",
                  :path => ":rails_root/public/assets/products/:id/:style/:basename.:extension"

1 个答案:

答案 0 :(得分:5)

是的,你可以用回形针做到这一点。我这样做的方式是使用嵌套资源和nested_form gem。

例如,您building has_many :photosphoto belongs_to :building

然后在你的/views/buildings/_form.html.erb中你会写这样的东西:

<%= nested_form_for @building, :html => { :multipart => true } do |f| %>
  <%# all your building fields .... %>

  <%= f.fields_for :photos do |photo| %>  
    <% if photo.object.new_record? %>
      <%= photo.file_field(:image) %>
    <% else %> 
      <%= image_tag(photo.url(:thumb)) %>
      <%= photo.hidden_field :_destroy %>
      <%= photo.link_to_remove "X" %>
    <% end %>
  <% end %>

  <p><%= f.link_to_add "Add photo", :photos %></p>

  <%= f.submit %>
<% end %>

您必须在accepts_nested_attributes_for :photos, :allow_destroy => true模型中设置building.rb,并确保routes.rb也包含嵌套:

resources :buildings do 
  resources :photos
end