繁体   English   中英

Ruby on Rails回形针多重上传,带有嵌套属性

[英]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_imagesTrip模型中。

将表单更改为以下形式:

= 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM