How to Upload Multiple Images in Rails 4 Using a Paperclip

I am trying to create an image gallery for my Markets controller here. I can use paperclip to upload a single image. I am searching on google, but I have not found any solution. How to upload multiple images and display them as a gallery using paperclip. there anyway. Please offer me an answer.

+4
source share
1 answer

Here is an article that explains in detail how to achieve it. Below are some snippets of code.

Models:

# 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

View:

# 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 %>

Controller:

# 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
+4
source

Source: https://habr.com/ru/post/1618733/


All Articles