2015-12-05 42 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

嘿,我无法保存图像,请你解释我该如何显示图像。它不被保存在公共/图像 –

相关问题