带有多个图像的嵌套回形针形式 [英] Nested paperclip form with multiple images

查看:99
本文介绍了带有多个图像的嵌套回形针形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在香蕉模型和图像模型之间存在一对多关联.

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

我想要一个嵌套的表单来创建香蕉和图像.更重要的是,我不知道要构建多少个图像(请注意Multiple属性).下表中注释掉的位将创建适当数量的图像,但不会完成关联的用户参考. 有没有办法像我尝试的那样用fields_for完成此操作(以便完成关联)?

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?

BAANAA模型

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

图像模型

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

  belongs_to :banana
  validates_presence_of :banana

  has_attached_file :img
end

表格

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

推荐答案

在ror中使用Paperclip多次上传

检查此答案!

您可以使用回形针上传图片和

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.

这篇关于带有多个图像的嵌套回形针形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆