Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple models in the same form in Rails 3.1?

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!

like image 554
jasonbogd Avatar asked Sep 02 '11 22:09

jasonbogd


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 this

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

Then in your Topic controller add this

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

That should get you going.

like image 160
Dty Avatar answered Oct 17 '22 17:10

Dty


A very good explanation from Ryan Bates here and here

For your particular case: you are using a model (:post), instead of an association (:posts) when you call fields_for.

Also check for the proper use of <%= ... %>. In rails 3.x the bahaviour of the construct changed. Block helpers (form_for, fields_for, etc) dont need it, and inline helpers (text_field, text_area, etc) do need it.

like image 22
Pablo Castellazzi Avatar answered Oct 17 '22 15:10

Pablo Castellazzi