I am reading this tutorial : http://sleekd.com/general/adding-multiple-images-to-a-rails-model-with-paperclip/
because i need Save the product images in a independent model. However when Product.create execute don´t save the data for product images model.
NOTE: I use the new pack action because i need to use ajax for create a new product.
Please I need Help.
My Code
Controllers
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
View
<% 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 %>
Models
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
You can’t upload files using AJAX, just like you said. There are, however, alternate solutions.
The common technique to accomplish this is the usage of an iframe. Have a look here, this tutorial is oriented towards attachment_fu but it’ll work with paperclip as well. Uploadify is worth checking out and can also be used with paperclip on rails 2.3 and rails 3.