Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
670 views
in Technique[技术] by (71.8m points)

ruby on rails - Nested paperclip form with multiple images

I have a one-to-many association between a Banana model and an Image model.

In addition, each Banana and Image belong to a User (via a separate association because an Image and its Banana might have different Users).

I would like a nested form to create Bananas as well as Images. The kicker is that I don't know how many Images to build (note the multiple attribute). The commented out bit of the form below will create the appropriate amount of Images, but won't complete the associated User reference. Is there a way to accomplish this with fields_for (so the associations are completed) as I've attempted?

BANANA MODEL

class Banana < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :user

  has_many :images, dependent: :destroy
  accepts_nested_attributes_for :images
  validates_associated :images
end

IMAGE MODEL

class Image < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :user

  belongs_to :banana
  validates_presence_of :banana

  has_attached_file :img
end

FORM

<%= form_for @banana, :validate => true, :html => { :multipart => true } do |f| %>
<!--    <input type="file" name="banana[images_attributes][][img]" multiple />-->
    <%= f.fields_for 'images_attributes[]', @banana.images do |builder| %>
        <%= builder.file_field :img, multiple: true %>
    <% end %>
<% end %>

CONTROLLER

class BananasController < ApplicationController
  def create
    @banana = current_user.bananas.build(banana_params)
    render :new unless @banana.save
  end

  def new
    @banana = Banana.new
  end

  private

  def banana_params
    params.required(:banana).permit(images_attributes: [:img])
  end
end
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Multiple upload with Paperclip in ror

Check this answer!

You may use paperclip to upload pics and nested_form for multiple uploading. The question above will help you to connect all this. If still you can't do it, write me. I'm just solve that issue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...