Validation in a "subform"

I’ve been following the rails/osx tutorial at

This develops a simple application with expenses and accounts.

Near the end of the tutorial, there is a view which allows expenses to
be added to an account.

This view has the “parent” @account rendered, then iterates throught
@account.expenses to display the existing accounts, then has a form.

<%= start_form_tag :action => ‘record’, :id => @account %>

On <%= date_select 'expense', 'paid_on', :order => [:month, :day, :year] %> to <%= text_field 'expense', 'payable_to', :size => 25 %> in the amount of $<%= text_field 'expense', 'amount', :size => 9 %>

<%= submit_tag 'Record!' %> <%= end_form_tag %>

Which then calls the record action in the controller:

def record
Account.find(params[:id]).expenses.create(params[:expense])
redirect_to :action => ‘show’, :id => params[:id]
end

and all is well. Very neat.

Except when you try to validate something in the new expense.

I’ve tried replacing the hand coded expense form with the partial in
/expenses/form (which has the “error_messages_for ‘expense’ line”),
but the validation messages don’t show up. The record is validated,
but the rendering of the error messages (and the nice red lines!)
don’t show.

I would be grateful for help! I wonder if it’s due to the page being
unable to find the expenses instance…

Thanks very much

Chris

it’s because this case is not handled in the “record” function. You
sould
have more something like:

def record
if Account.find(params[:id]).expenses.create(params[:expense])
redirect_to :action => ‘show’, :id => params[:id]
else
render :action => modifyAccount
end
end

the idea is to say “everything ok”? go there
Something wrong? display message

You can check how the scaffold do that.