Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - paperclip - Multiple photo upload not saving

I'm trying to make a create product page in rails. This includes adding multiple images and text fields. I have one model for products and one for photos. I'm using the paperclip gem for photo upload. But I get no picture when I view product page. Photos are not being saved to database.

P.S. I use HAML.

app/views/products/show.html.haml

  %b Name
  = @product.name
  %br

  %b Description
  = @product.description

  %br
  - @product.photos.each do |photo|
  = image_tag photo.image.url

app/controllers/products_controller

class ProductsController < ApplicationController
  before_filter :require_login
    before_filter :current_user, only: [:create, :destory]

  def new 
    @product = Product.new
    @photo = Photo.new
    5.times { @product.photos.build }
  end

  def create

  @photo = current_user.photos.build(params[:photo])
  @product = current_user.products.build(params[:product])
    if @product.save
        render "show", :notice => "Sale created!"
    else
        render "new", :notice => "Somehting went wrong!"
    end
end

  def show
    @product = Product.find(params[:id]) 
  end

app/models/photo

class Photo < ActiveRecord::Base
  attr_accessible :product_id    
  belongs_to :product
  has_attached_file :image,
    :styles => {
      :thumb=> "100x100#",
      :small  => "300x300>",
      :large => "600x600>"
        }
end

app/models/product

class Product < ActiveRecord::Base
  attr_accessible :description, :name, :price, :condition, :ship_method, :ship_price, :quantity, :photo
  has_many :photos, dependent: :destroy
  accepts_nested_attributes_for :photos
  belongs_to :user
end

user model

   class User < ActiveRecord::Base
      attr_accessible :email, :password, :password_confirmation, :name

      attr_accessor :password
      has_many :products, dependent: :destroy
      has_many :photos,:through=>:products

app/products/new.html.haml

= form_for @product, :html => { :multipart => true } do |f|
  %p
    = fields_for :photos do |f_i|
      =f_i.file_field :image 
like image 608
Alain Goldman Avatar asked May 11 '13 19:05

Alain Goldman


1 Answers

First your form is wrong, q for registration of photos used fields_for, then you use fields_for f.object.photos or use Photo.new do | g |, the other in your relationship model is wrong has_attached_file is has_many photos, the has_attached_file Paperclip is proper to be used in the model to be used not in the relationship with the other model. Hope this helps, now to have a product with several photographs, I recommend you use the gem cocoon, I q goes according to your case, https://github.com/nathanvda/cocoon

like image 166
Huascar Ernesto Mamani Avatar answered Sep 20 '22 15:09

Huascar Ernesto Mamani