Forum: Ruby on Rails validation in a "subform"

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Chris Wright (Guest)
on 2006-05-29 16:18
(Received via mailing list)
I've been following the rails/osx tutorial at

http://developer.apple.com/tools/rubyonrails.html

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 %>
  <p>
    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 %>
  </p>
  <%= 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
Nicolas B. (Guest)
on 2006-05-29 19:43
(Received via mailing list)
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.
This topic is locked and can not be replied to.