2011-02-03 2 views
0

이 자습서는 http://sleekd.com/general/adding-multiple-images-to-a-rails-model-with-paperclip/ 이므로 독립적 인 모델로 저장해야합니다. 그러나 Product.create가 실행될 때 제품 이미지 모델의 데이터를 저장하지 마십시오.아약스가있는 문제 클립

참고 : 새 제품을 만들 때 ajax를 사용해야하므로 새 팩 작업을 사용합니다.

제발 도와주세요.

내 코드

컨트롤러

class Admin::PacksController < ApplicationController 
     def new 
     @pack = Pack.new 
     @product = Product.new 
     4.times {@product.product_images.build} # added this 
     respond_to do |format| 
      format.html # new.html.erb 
      format.xml { render :xml => @pack } 
     end 
     end 

     def create_starred_product 
     product = Product.new(params[:product]) 
     product.save 
... 

     end 

보기

<% form_remote_for @product, :url => {:controller => "products", :action => "create_starred_product"}, :html => {:multipart => true} do |f| %> 
     <div id="content"> 
....#OTHER FIELDS OF PRODUCT. ITS SAVE METHOD IS OK 
     <div id="images-selector"> 
      <span class="fleft">Imágenes</span><br/> 
      <% count = 0 %> 
      <% f.fields_for :product_images do |builder| %> 

       <% if builder.object.new_record? %> 
        <label> 
        Imagen <%= "#{count = count + 1}" %> 
        </label> 
        <%= builder.file_field :photo, :class => "textarea" -%><br/> 
       <% end %> 
      <% end %> 
     </div> 
     <p><%= f.submit "Crear" %></p> 
     </div> 
    <% end %> 

모델

class Product < ActiveRecord::Base 
    has_many :packs, :through => :pack_products 
    has_many :product_images, :dependent => :destroy 
    #PAPERCLIP 
    accepts_nested_attributes_for :product_images, :reject_if => lambda { |t| t['product_image'].blank? } 
end 

class ProductImage < ActiveRecord::Base 
    belongs_to :product 
    has_attached_file :photo, :url => "/:attachment/:class/:id/:style_:basename.:extension", :styles => { :medium => "300x300>", :thumb => "100x100>", :small => "30x30>" } 
end 
+0

실례합니다. 제목에 오류가 있습니다. 실감하지 않았습니다. 문제는 클립과 Ajax에 관한 것입니다. 이제 나는 클립 클립을 읽었고 아약스는 (자바 스크립트 보안 모델) 함께 작동하지 않으므로 대안 솔루션이 필요하다. 감사합니다 – maxiperez

답변

2

당신은 당신이 말한 것처럼, AJAX를 사용하여 파일을 업로드 할 수 없습니다. 그러나 대체 솔루션이 있습니다.

이 작업을 수행하는 일반적인 방법은 iframe을 사용하는 것입니다. here을 보시고이 튜토리얼은 attachment_fu를 지향하지만 클립 클립도 사용할 수 있습니다. Uploadify은 체크 아웃 할 가치가 있으며 rails 2.3rails 3에 클립과 함께 사용할 수도 있습니다.

+0

jQuery 양식 플러그인을 통해 여러 부분 정보를 보낼 수있는 양식을 할 수 있습니다. 이제는 구할 수 없었습니다. 왜?. 내 모델은 bas 또는 컨트롤러입니다. 클립 클립의 이미지를 저장해야합니다. – maxiperez

+0

내가 말한 것으로 인해 이미지가 제대로 전송되지 않았기 때문에 저장할 수 없습니다. 내가 남긴 링크를 탐색 했니? 그렇지 않다면, 그들에게 보이게하십시오. – goncalossilva

0

해결책을 찾았습니다.

내 오류가 Ajax.so의 중첩 된 속성 양식에 있습니다. Ajax와 함께 클립 사용에 대한 해결책을 찾았습니다. 이제 예제 코드를 게시했습니다.

그러나 코드를 설명합니다.

모델

두 가지 모델

제품 및 Product_images

내가 원했던 내가 아약스 형태의 제품 (팩 belongs_to 각 제품)를 만들 때. 각 제품에는 product_images 모델에 많은 이미지가 있습니다. 따라서 이미지 저장도 원했습니다.

코드

컨트롤러 아약스 액션

class ProductsController < ApplicationController 
     def create_starred_product 
     product = Product.new(params[:product]) 
     product.save 

     render :update do |page| 
      page.replace_html 'star-product', :partial => "admin/products/star_product_name", :locals => {:star_product => product} 
      page.call "$j.modal.close" 
     end 
end 

    end 

모델

제품 모델

class Product < ActiveRecord::Base 
    has_many :packs, :through => :pack_products 
    has_many :product_images, :dependent => :destroy 

    #PAPERCLIP 
    accepts_nested_attributes_for :product_images#, :reject_if => lambda { |t| t['product_image'].blank? } 

    has_attached_file :photo, :url => "/:attachment/:class/:id/:style_:basename.:extension", :styles => { :medium => "300x300>", :thumb => "100x100>", :small => "30x30>" } 

Product_images 모델

class ProductImage < ActiveRecord::Base 
    belongs_to :product 

    has_attached_file :photo, :url => "/:attachment/:class/:id/:style_:basename.:extension", :styles => { :medium => "300x300>", :thumb => "100x100>", :small => "30x30>" } 
end 

end 
01 아약스에서 23,516,

보기 팝업 (이이 부분입니다)

<script type="text/javascript"> 
    $j(document).ready(function() { 
     $j('#product_submit').click(function(event) { 
      event.preventDefault(); 
      $j('#uploadForm').ajaxSubmit({ 
       beforeSubmit: function(a, f, o) { 
        o.dataType = 'json'; 
       }, 
       complete: function(XMLHttpRequest, textStatus) { 
        // XMLHttpRequest.responseText will contain the URL of the uploaded image. 
        // Put it in an image element you create, or do with it what you will. 
        // For example, if you have an image elemtn with id "my_image", then 
        // $('#my_image').attr('src', XMLHttpRequest.responseText); 
        // Will set that image tag to display the uploaded image. 
       } 
      }); 
     }); 
    }); 
</script> 
<div id="new-starred-product" class="popup clearfix"> 
    <div id="header">Nuevo producto estrella</div> 
    <% remote_form_for @product, :url => {:controller => "products", :action => "create_starred_product"}, :html => {:method => :post, :id => 'uploadForm', :multipart => true} do |f| %> 
     <div id="content"> 
     <label>Nombre:</label> <%= f.text_field :name, :class => "textarea" %> 
     <br/> 
     <label>Precio:</label> <%= f.text_field :price, :class => "textarea" %> 
     <br/> 
     <%#= f.file_field :photo %> 
     <div id="images-selector"> 

      <% count = 0 %> 
      <%# f.fields_for "product_images_attributes[]", ProductImage.new do |builder| %> 
      <% f.fields_for :product_images, 4.times {ProductImage.new} do |builder| %> 
       <% if builder.object.new_record? %> 
        <label> 
        Imagen <%= "#{count = count + 1}" %> 
        </label> 
        <%= builder.file_field :photo, :class => "file-upload" -%><br /> 
        <br/> 
       <% end %>    
       <%#= builder.text_field :testfield %> 
<!--ACA VA EL CODIGO PARA IMAGENES--> 
      <% end %> 
     </div> 
     <br/> 
     <label>Descripción</label><%= f.text_area :description, :rows => 10, :class => "textarea clearfix" -%> 
     <br/> 

     <p> 
      <%#= f.submit "Crear" %> 
     <%= link_to "Crear", "#", :id => "product_submit" %> 
     </p> 
     </div> 
    <% end %> 
</div> 

나는 JQuery와 및 JQuery와 양식 플러그인을 사용하고

0

문제는 중첩되었다 속성이 나는 같은 문제를 했어 때 방금 발견 한이 문제에 도움이 코드를

0

또 다른 보석을 게시 form.later 것은 remotipart입니다 - 매우 좋습니다.