4

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 .

1 Answer 1

6

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

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
Sign up to request clarification or add additional context in comments.

6 Comments

How do you add validations?
@liroy I think by adding validations to Picture model.
Hey I am unable to save image will you please explain how can i show that images . It is not getting saved under public/image
Paperclip::AdapterRegistry::NoHandlerError in HousesController#create what to do ?
@Nischaynamdev google the error to see possible solutions? :) I haven't met this error before, so won't tell for sure what to do unfortunately.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.