2013-07-13 2 views
1

@product 함께 중첩 된 @photo 두 제품 @product 및 @photo 있습니다. 나는 하나의 양식을 사용하여 두 가지를 모두 만들 수 있습니다. 나는 그것이 좋은 미리보기를주는 방법 인 사진 업로드를 처리하기 위해 this JQuery plugin를 사용하고있다.하나의 중첩 된 form_for 만들기 두 개의 다른 컨트롤러를 사용

그러나 플러그인에는 사진 작성과 제품 작성을 모두 처리 할 수있는 제품 작성 조치를 사용할 수 없어서 작성 활동에 특정 제한 사항이 있습니다.

  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 

답변

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

사용 아약스는 먼저 사진을 업로드하고 성공적인 응답 후 제품과 함께 계속합니다.

+0

나는 어떤 종류의 예제를 얻을 수 있습니까 ?? –

관련 문제