I am using Rails 3.1 and am working on a discussion forum. I have a model called Topic, each of which has many Posts. When the user makes a new topic, they should also make the first Post as well. 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 doesn’t seem to be working. Any ideas?
Thanks!
@Pablo’s answer seems to have everything you need. But to be more specific…
First change this line in your view from
to this
Then in your
Topiccontroller add thisThat should get you going.