[英]Ruby on Rails paperclip multiple upload with nested attributes
I was wondering if someone can help me with file uploading! 我想知道是否有人可以帮助我进行文件上传!
I'm trying to upload multiple images using paperclip and having nested attributes. 我正在尝试使用回形针上传多个图像并具有嵌套属性。
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 %>
How do I save multiple images in my trip image database? 如何在旅行图像数据库中保存多个图像? When I submit the form, nothing gets saved into the database.
当我提交表单时,什么都没有保存到数据库中。
Add :trip_id
to trip_images_attributes
: 将
:trip_id
添加到trip_images_attributes
:
def trip_params
params.require(:trip).permit(
:user_id,
trip_images_attributes: [:trip_id, :id, :photo]) # :_destroy
end
Also you can add :_destroy
if you plan to be able to remove photos. 如果您打算删除照片,也可以添加
:_destroy
。
What you also missed is to add accepts_nested_attributes_for :trip_images
to Trip
model. 您还缺少的是将
accepts_nested_attributes_for :trip_images
添加到accepts_nested_attributes_for :trip_images
到Trip
模型中。
Change your form to something like this: 将表单更改为以下形式:
= f.simple_fields_for :trip_images do |tp|
= render 'trip_photos_fields', f: photo
.links
%br= link_to_add_association 'Add another photo', f
And _trip_photos_fields.html.haml
partial: 和
_trip_photos_fields.html.haml
部分:
- unless f.object.new_record?
%br= link_to_remove_association "Delete photo", f
= link_to image_tag(f.object.photo.url(:medium)), f.object.photo.url, target: '_blank'
- if f.object.new_record?
= f.file_field :photo, as: :file
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.