如何在rails项目上向ruby添加其他文件字段?

时间:2012-04-29 10:58:15

标签: ruby ruby-on-rails-3

昨天我制作了回形针多个上传图库。今天我想自定义这一切,我需要点击一下按钮再添加一个文件上传字段。您可以在此视频中看到示例:http://www.emersonlackey.com/article/rails-paperclip-multiple-file-uploads 28:27。

我在google搜索过,但找不到任何内容。

@post form:

   <% form_for @post, :html => {:multipart => true}  do |t| %>
            <p>
                <%= t.label :title, 'Virsraksts:' %></br>
                <%= t.text_field :title %></br>
            </p>
            <p>
                <%= t.label :content, 'Teksts:' %>
                <%= t.text_area :content, :class => "mceEditor"%>
            </p>

            <p>Pievienot jaunas bildes:</p>
            <%= f.link_to_add "Add a task", :assets %>
            <%= f.fields_for :assets do |asset_fields| %>           
                <% if asset_fields.object.new_record? %>
                    <%= asset_fields.file_field :asset %>
                    <%= asset_fields.link_to_remove "Noņemt" %>
                <% end %>
            <% end %>

            <p>
                <%= f.fields_for :assets do |asset_fields| %>
                    <% unless asset_fields.object.new_record? %>
                    <p>
                        <%= link_to image_tag(asset_fields.object.asset.url(:thumb)), asset_fields.object.asset.url(:original) %>
                        <%= asset_fields.check_box :_destroy %>
                    </p>
                    <% end %>
                <% end %>
            </p>    
        <%= t.submit %>

@post model:

class Post < ActiveRecord::Base
  attr_accessible :title, :content, :assets_attributes
    has_many :assets
    accepts_nested_attributes_for :assets, :allow_destroy => true 
end

@asset model:

class Asset < ActiveRecord::Base
  belongs_to :post
  has_attached_file :asset, :styles => { :large => "640x480", :medium => "300x300>", :thumb => "100x100>" },
                        :url => "/assets/albums/:id/:style/:basename.:extension",
                        :path => ":rails_root/public/assets/albums/:id/:style/:basename.:extension"
  accepts_nested_attributes_for :post, :allow_destroy => true 
end

2 个答案:

答案 0 :(得分:2)

来自R.Bates的关于嵌套形式here的精彩演员。我已对其进行了修改,以便现在可以添加,删除照片,使用回形针,随意克隆此rails3.2 app https://github.com/Saidbek/multiple-image-uploader

答案 1 :(得分:1)

您将需要使用javascript来使函数正常工作。

如果您是railscasts高级用户,您可以访问上面的链接,如所建议的那样,但如果您不是,则应该查看this link