我正在尝试为我的市场控制器创建一个图像库我可以使用回形针上传单个图像.我在谷歌上搜索但我找不到任何解决方案.如何使用回形针上传多个图像并以图库的形式显示.有什么办法吗?请给我答案.
这篇文章详细解释了如何实现它.下面是一些代码片段.
楷模:
# 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| %><%= f.label :pictures, class: "control-label" %><%= file_field_tag "images[]", type: :file, multiple: true %><%= f.submit nil, class: "btn btn-primary" %> <%= link_to t(".cancel", default: t("helpers.links.cancel")), galleries_path, class: "btn btn-mini" %><% 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