如何使用回形针在Rails 4中上传多个图像 [英] How to Upload Multiple Image in Rails 4 Using Paperclip

查看:77
本文介绍了如何使用回形针在Rails 4中上传多个图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的Markets控制器创建一个图像画廊,在这里我能够使用回形针上传单个图像.我在google上搜索,但找不到任何解决方案.如何使用回形针上传多张图像并以图库的形式显示.有什么办法吗.请给我建议答案.

I am trying to create a gallery of Images for my Markets controller here I am able to to use paperclip to upload single image .I search on google but I haven't find any solution . How can I upload multiple images and show it in the form of gallery using paperclip . is there any way . Please suggest me the answer .

推荐答案

此处为文章,其中详细说明了如何实现. 下面是一些代码片段.

Here is the article, which explains in details, how to achieve it. Some code snippets from there are below.

型号:

# app/models/market.rb
class Market < ActiveRecord::Base
  has_many :pictures, dependent: :destroy
end

# app/models/picture.rb
class Picture < ActiveRecord::Base
  belongs_to :market

  has_attached_file :image,
    path: ":rails_root/public/images/:id/:filename",
    url: "/images/:id/:filename"

  do_not_validate_attachment_file_type :image
end

查看:

# app/views/markets/_form.html.erb
<%= form_for @market, html: { class: "form-horizontal", multipart: true } do |f| %>
  <div class="control-group">
    <%= f.label :pictures, class: "control-label" %>
    <div class="controls">
      <%= file_field_tag "images[]", type: :file, multiple: true %>
    </div>
  </div>

  <div class="form-actions">
    <%= f.submit nil, class: "btn btn-primary" %>
    <%= link_to t(".cancel", default: t("helpers.links.cancel")),
                galleries_path, class: "btn btn-mini" %>
  </div>
<% end %>

控制器:

# app/controllers/markets_controller.rb
def create
  @market = Market.new(market_params)

  respond_to do |format|
    if @market.save

      if params[:images]
        params[:images].each { |image|
          @market.pictures.create(image: image)
        }
      end

      format.html { redirect_to @market, notice: "Market was successfully created." }
      format.json { render json: @market, status: :created, location: @market }
    else
      format.html { render action: "new" }
      format.json { render json: @market.errors, status: :unprocessable_entity }
    end
  end
end

这篇关于如何使用回形针在Rails 4中上传多个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆