Multiple models in one form in Rails 3.1?

I use Rails 3.1 and work in a discussion forum. I have a model called Topic, each of which has a set Posts. When a user creates a new topic, they must also do the first Post. However, I am not sure how I can do this in the same form. Here is my code:

<%= form_for @topic do |f| %>
<p>
    <%= f.label :title, "Title" %><br />
    <%= f.text_field :title %>
</p>

<%= f.fields_for :post do |ff| %>
    <p>
        <%= ff.label :body, "Body" %><br />
        <%= ff.text_area :body %>
    </p>
<% end %>

<p>
    <%= f.submit "Create Topic" %>
</p>
<% end %>

class Topic < ActiveRecord::Base
  has_many :posts, :dependent => :destroy
  accepts_nested_attributes_for :posts
  validates_presence_of :title
end


class Post < ActiveRecord::Base
  belongs_to :topic
  validates_presence_of :body
end

... but this does not seem to work. Any ideas?

Thank!

+5
source share
2 answers

@Pablo's answer seems to have everything you need. But to be more specific ...

First change this line in your view from

<%= f.fields_for :post do |ff| %>

to that

<%= f.fields_for :posts do |ff| %>  # :posts instead of :post

Then in your controller Topicadd this

def new
  @topic = Topic.new
  @topic.posts.build
end

.

+6

: (: post) (: posts) fields_for.

<%= ... %>. 3.x . (form_for, fields_for ..) , (text_field, text_area ..) .

+3

All Articles