根据上传的文件显示上传按钮

时间:2013-11-27 12:26:28

标签: ruby-on-rails ruby ruby-on-rails-3 file-upload ruby-on-rails-4

我有一个项目模型,我可以在其中创建项目,并为每个项目上传视频和照片。我正在使用嵌套属性。我的表单显示5个照片上传按钮和5个视频上传按钮。我想隐藏使用的按钮。例如:如果我上传了1张照片和2个视频,我希望我的编辑表单能够显示4个上传照片按钮和3个视频按钮。

现在,如果上传照片,它会隐藏照片中的1个上传按钮和视频中的1个上传按钮。有谁知道如何做到这一点?

这是我的控制器。

 def new
        @project = Project.new()
        (5 - @project.assets.length).times { @project.assets.build }


        respond_to do |format|
          format.html # new.html.erb
          format.xml  { render :xml => @project }
        end


      end

      # GET /projects/1/edit
      def edit
          @project = Project.find_by_permalink(params[:id])
          (5 - @project.assets.length).times { @project.assets.build }


      end

宝石:

gem "paperclip", "~> 3.5"

# handels video upload
gem "paperclip-ffmpeg", "~> 1.0.0"

项目模型:

class Project < ActiveRecord::Base
    has_permalink :title
    default_scope :order => 'created_at desc'
    attr_accessible :title, :description, :assets_attributes, :dependent => :destroy
    validates_uniqueness_of :title
    validates_presence_of :title
    has_many :assets, :dependent => :destroy
    accepts_nested_attributes_for :assets, :allow_destroy => true

end

资产模型:

class Asset < ActiveRecord::Base
    require 'paperclip'
    require 'paperclip-ffmpeg'

    belongs_to :project, :foreign_key => "project_id"
    attr_accessible :project_id, :photo, :video
    has_attached_file :photo, :styles => {  :thumb => "130x130#", :medium => "300x300#", :small => "160x160#"}
    has_attached_file :video, :styles => {
    :mobile => {:geometry => "400x300", :format => 'flv', :streaming => true}
  }, :processors => [:ffmpeg, :qtfaststart]   


end

2 个答案:

答案 0 :(得分:0)

您需要区分视频资产和图片资产。那样做。 此外,如果您可以与我们分享使用的宝石,我们可以提供更好的帮助。

答案 1 :(得分:0)

通过制作“添加”按钮解决问题,根据请求添加文件字段。(视频上传和视频上传一个。)

<div class="row">
  <div class="newPaperclipFiles col-md-4 col-md-offset-1" style="overflow: hidden;">
    <h3 style="color:rgb(31,154,207);">Upload a Photo</h3>
    <hr style="margin-left: -20%; width: 280px !important;"></hr>
    <%= f.fields_for :assets do |asset_photo| %>
      <% if asset_photo.object.new_record? %>
        <div class="btn custumbtn btn-xs" id="duplp" onlick="duplicatep()">Add</div>
        <div id="duplicaterp"> 
          <%= asset_photo.file_field :photo %>
        </div>
      <% end %>
    <% end %>
  </div>
</div>

JS:

<script type="text/javascript">
document.getElementById('duplp').onclick = duplicatep;

var i = 0;
var original = document.getElementById('duplicaterp');

function duplicatep() {
    var clone = original.cloneNode(true);
    clone.id = "duplicaterp" + ++i;
    original.parentNode.appendChild(clone);
}
</script>