gpt4 book ai didi

ruby-on-rails - 如何使用 Paperclip 在 Rails 4 中上传多个图像

转载 作者:行者123 更新时间:2023-12-04 05:38:09 28 4
gpt4 key购买 nike

我正在尝试为我的 Markets Controller 创建一个图像库,我可以使用回形针上传单个图像。我在谷歌上搜索,但没有找到任何解决方案。如何上传多张图片并使用回形针以图库的形式显示。有什么办法。请给我建议答案。

最佳答案

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

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

关于ruby-on-rails - 如何使用 Paperclip 在 Rails 4 中上传多个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34110469/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com