[英]Ruby on Rails paperclip multiple upload with 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 %>
如何在旅行圖像數據庫中保存多個圖像? 當我提交表單時,什么都沒有保存到數據庫中。
將:trip_id
添加到trip_images_attributes
:
def trip_params
params.require(:trip).permit(
:user_id,
trip_images_attributes: [:trip_id, :id, :photo]) # :_destroy
end
如果您打算刪除照片,也可以添加:_destroy
。
您還缺少的是將accepts_nested_attributes_for :trip_images
添加到accepts_nested_attributes_for :trip_images
到Trip
模型中。
將表單更改為以下形式:
= f.simple_fields_for :trip_images do |tp|
= render 'trip_photos_fields', f: photo
.links
%br= link_to_add_association 'Add another photo', f
和_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.