Ruby on Rails回形针具有嵌套属性的多个上传

时间:2015-07-20 07:11:51

标签: ruby-on-rails ruby ruby-on-rails-4 paperclip 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 %>

如何在旅行图像数据库中保存多个图像?当我提交表单时,没有任何内容保存到数据库中。

1 个答案:

答案 0 :(得分:5)

: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添加到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