制作一个嵌套的form_for使用两个不同的控制器

时间:2013-07-13 21:09:24

标签: ruby-on-rails ruby

我有两个型号@product和@photo,@ photos嵌套在@product中。我只允许使用一个表单来创建它们。我正在使用this JQuery plugin处理照片上传,因为它为我提供了很好的预览效果。

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

  1. 是否可以让一个嵌套的for_for使用两个不同的控制器?
  2. 我该怎么做?
  3. 我的表格(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
    

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:-1)

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