2015-12-05 68 views
4

我想在這裏爲我的市場控制器創建圖片庫我能夠使用回形針上傳單個圖像。我在谷歌上搜索,但是我沒有找到任何方案。如何上傳多個圖像並使用回形針以圖庫的形式顯示它。有沒有辦法。請給我答案。如何在Rails 4中上傳多個圖像4使用回形針

回答

3

Here is the article,其中詳細解釋瞭如何實現它。以下是一些代碼片斷。

型號:

# 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 
+0

你如何添加驗證? – Liroy

+1

@liroy我認爲[添加驗證](https://github.com/thoughtbot/paperclip#validations)到'Picture'模型。 –

+1

嘿,我無法保存圖像,請你解釋我該如何顯示圖像。它不被保存在公共/圖像 –

相關問題