1

我有两个模型@product 和@photo,@photo 嵌套在@product 中。我只能使用一种形式来创建两者。我正在使用这个 JQuery 插件来处理照片上传,因为它给了我一个很好的预览。

但是该插件在我的创建操作中有某些限制,因此我不能使用产品创建操作来处理创建照片和产品。

  1. 是否可以让一个嵌套的 for_for 使用两个不同的控制器?
  2. 我该怎么做?

我的表格 (haml)

= form_for @product,:url => products_path, :html => { id: "fileupload", multipart: true } do |f| 
  %p
    = f.text_field :name, placeholder: "Name"
  %p
    = f.text_field :price, class: "auto", data: { a_sign: "$ " }, placeholder: "Price" 
  %p
    = f.text_field :description, placeholder: "Description"
  %p
    = f.fields_for :photos do  |fp| 
      =fp.file_field :image
      %br

  .files{"data-target" => "#modal-gallery", "data-toggle" => "modal-gallery"}
  %p.button.start
    = f.submit
4

2 回答 2

1
You can use accept_nested_attributes for to save associated data with only one create action.

Eg:-
class AlbumsController < ApplicationController
  def new
    @album = Album.new
    @album.photos.build
  end

  def create
    @album = Albums.new(params[:album])
    @album.photos.build unless @album.photos.present?
    if @album.save  
      flash[:notice] = "Successfully created albumn"
      respond_with(@album, :location => albums_path())
    else
      flash[:error] = @album.errors.full_messages
      render :new
    end
  end
end

Model:-

class Album < ActiveRecord::Base
  has_many :photos, dependent: :destroy
  accepts_nested_attributes_for :photos, allow_destroy: true, reject_if: proc {|attr|  attr['image'].blank? }
end

class Photo < ActiveRecord::Base
  belongs_to :album
end

View:-
= form_for @album,:url => albums_path, :html => {multipart: true } do |f| 
  %p
    = f.text_field :name, placeholder: "Name"
  %p
    = f.text_field :price, class: "auto", data: { a_sign: "$ " }, placeholder: "Price" 
  %p
    = f.text_field :description, placeholder: "Description"
  %p
    = f.fields_for :photos do  |photo| 
      = photo.file_field :image
      %br

  .files
  %p.button.start
    = f.submit
于 2013-07-15T07:42:23.603 回答
-1

使用ajax首先上传照片,成功响应后继续产品。

于 2013-07-13T21:18:41.610 回答