hel*_*llo 2 ruby ruby-on-rails paperclip nested-attributes ruby-on-rails-4
我想知道是否有人可以帮助我上传文件!
我正在尝试使用回形针上传多个图像并具有嵌套属性.
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
<%= 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 %>
Run Code Online (Sandbox Code Playgroud)
如何在旅行图像数据库中保存多个图像?当我提交表单时,没有任何内容保存到数据库中.
添加:trip_id到trip_images_attributes:
def trip_params
params.require(:trip).permit(
:user_id,
trip_images_attributes: [:trip_id, :id, :photo]) # :_destroy
end
Run Code Online (Sandbox Code Playgroud)
:_destroy如果您打算删除照片,也可以添加.
您还错过了添加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
Run Code Online (Sandbox Code Playgroud)
而_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
Run Code Online (Sandbox Code Playgroud)