0

I am working on Rails 3.1.1.rc3 and I have 2 classes as shown below.

class Customer < ActiveRecord::Base
  has_many :orders, :dependent => :destroy
  accepts_nested_attributes_for :orders
end

class Order < ActiveRecord::Base
  belongs_to :customer
end

In my form:

<%= form_for(@customer) do |f| %>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name,:class=>'textbox' %>
  </div>

  <%= f.fields_for :orders do |order_form| %>   
    <div class="field">
       <%= order_form.label :number %><br />
       <%= order_form.text_field :number, :class=>'textbox' %>
   </div>  
  <%end%>

<%end%>

When it renders, the first part of the form (for customer) shows up, but the second part (for order) doesn't. Any pointers are appreciated. Thanks.

1
  • For anyone who is interested, this is a very good article.link here Commented Dec 21, 2011 at 3:10

2 Answers 2

4

Two things. First fields_for basically iterates over customer.orders so if there are no orders you'll get no output. If you just want some blank fields for users to input order details you'd typically stick

@customer.orders.build

In your controller. Secondly, fields_for is very similar to form_for, you need to use <%= for it too

Sign up to request clarification or add additional context in comments.

Comments

1

add

<%= f.fields_for :orders do |order_form| %> 

instead of

<% f.fields_for :orders do |order_form| %> 

Edit: have a look at how fields_for is defined (there are examples there)

2 Comments

This is the right answer. In rails 3 you have to put = to helpers that generate any kind of output, like form_for, fields_for etc.
Just tried. The second form doesn't show up either. But that's a good points. Thanks. Edited my question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.