in a rails app I have a create product page which includes a nested form for photos. There are validations to make sure there is always a photo present. But, when I try to submit the form without a photo the product form rerendered without a photo input field.
New product page haml
= form_for @product,:url => products_path, :html => { :multipart => true } do |f|
- if @product.errors.any?
.error_messages
%h2 Form is invalid
%ul
- for message in @product.errors.full_messages
%li
= message
- if @photo.errors.any?
.error_messages
%h2 Image is invalid
%ul
- for message in @photo.errors.full_messages
%li
= message
%p
= f.label :description
= f.text_field :description
%p
= f.fields_for :photos do |fp|
=fp.file_field :image
%br
%p.button
= f.submit
products controller
class ProductsController < ApplicationController
def new
@product = Product.new
@photo = Photo.new
4.times{ @product.photos.build }
end
def create
@product = current_user.products.new(params[:product])
@photo = current_user.photos.new(params[:photo])
if @product.valid?
@product.save
@photo.product_id = @product.id
@photo.save
render "show", :notice => "Sale created!"
else
render "new", :notice => "Somehting went wrong!"
end
end
def edit
@product = Product.find(params[:id])
@photos_left = 4 - @product.photos.count
@new_photos = @photos_left.times.map{ @product.photos.build }
end
def update
@product = Product.find(params[:id])
if @product.update_attributes(params[:product])
render "show", :notice => "Sale editted!"
else
render "edit", :notice => "Failed"
end
end