【发布时间】:2015-07-20 07:11:50
【问题描述】:
我想知道是否有人可以帮助我上传文件!
我正在尝试使用回形针上传多张图片并具有嵌套属性。
模型
class Trip < ActiveRecord::Base
has_many :trip_images, :dependent => :destroy
end
class TripImage < ActiveRecord::Base
belongs_to :trip
has_attached_file :photo, :styles => { :large => "800x800>", :medium => "500x500>", :thumb => "150x150#" }, :default_url => "/images/:style/missing.png"
validates_attachment_content_type :photo, content_type: /\Aimage\/.*\Z/
end
控制器
def create
@trip = Trip.new(trip_params)
respond_to do |format|
if @trip.save
format.html { redirect_to @trip, notice: 'Trip was successfully created.' }
format.json { render :show, status: :created, location: @trip }
else
format.html { render :new }
format.json { render json: @trip.errors, status: :unprocessable_entity }
end
end
end
def trip_params
params.require(:trip).permit(
:user_id,
trip_images_attributes: [:id, :photo])
end
查看
<%= simple_form_for @trip, html: { multipart: true } do |f| %>
<%= f.simple_fields_for :trip_images do |p| %>
<%= p.file_field :photo, as: :file, multiple: true %>
<% end%>
<%= f.button :submit %>
<% end %>
如何在我的旅行图片数据库中保存多张图片?当我提交表单时,没有任何内容保存到数据库中。
【问题讨论】:
-
尝试将
trip_images_attributes: [:id, :photo])更改为trip_images_attributes: [:id, :photo => []]) -
并在
Trip模型中添加accepts_nested_attributes_for :trip_images。 -
您能发布一条请求创建操作的日志吗?
-
@Pavan 当我尝试这个时,我得到一个错误
No handler found for [#<ActionDispatch::Http::UploadedFile:0x007f9fdc112d98 @tempfile=#...我也尝试了@AndreyDeineko 的方法。但它只将 1 条记录保存到数据库中。 -
@AndreyDeineko 我做到了!我可以在有时间的时候提供一些信息.. 可能会将其发布在博客或其他内容中。我还没有看到太多关于 refile 的教程。但是,我无法实现 dropzonejs.. 那东西很头疼!
标签: ruby-on-rails ruby ruby-on-rails-4 paperclip nested-attributes