Alain Goldman
Alain Goldman

Reputation: 2908

Rails - cant add a photo with another model as an index

I'm trying to make a create product page that would allow users to upload photos. So products has_many photos. I got this set up but when a photo is added it should have product_id in a column but when it saves to my database the product_id column is blank.

product controller

  def create

  @product = current_user.products.build(params[:product])
  @photo = current_user.photos.new(params[:photo])

    if @product.valid? && @photo.valid?
      @product.save
      @photo.save
      @photo.product_id = @product.id
      render "show", :notice => "Sale created!"
    else
      render "new", :notice => "Somehting went wrong!"
    end
end

new product page(HAML)

%h1 
  create item
= form_for @product,:url => products_path, :html => { :multipart => true } do |f|         
  %p
    = f.label :name
    = f.text_field :name
  %p
    = f.label :description
    = f.text_field :description
  %p
    = fields_for :photo, :html => {:multipart => true} do |fp|
      =fp.file_field :image  

  %p.button
    = f.submit

schema.rb

  create_table "products", :force => true do |t|
    t.string   "name"
    t.text     "description"
    t.datetime "created_at",  :null => false
    t.datetime "updated_at",  :null => false
    t.integer  "user_id"
  end

  create_table "photos", :force => true do |t|
    t.integer  "product_id"
    t.datetime "created_at",         :null => false
    t.datetime "updated_at",         :null => false
    t.string   "image_file_name"
    t.string   "image_content_type"
    t.integer  "image_file_size"
  end

Upvotes: 0

Views: 45

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270617

This is merely a result of saving the @photo first, and then setting its product_id after saving, which of course never gets updated in the database. Just reverse the operations.

if @product.valid? && @photo.valid?
  # Recommended to test for success saving the product
  if @product.save
    # Set the product_id before saving
    @photo.product_id = @product.id
    # Then save the photo
    @photo.save
    render "show", :notice => "Sale created!"
  end
else
  render "new", :notice => "Somehting went wrong!"
end

Upvotes: 1

Related Questions