Search code examples
ruby-on-railsformtastic

How do I use multiple models in a form in Rails 3?


I'm new to Rails development. I have two models, Decision and Choice. Every decision has two choices, which should be added to the Choices table when the Decision is saved. I'm trying to figure out how to do this in Rails using Formtastic but I've hit a wall.

I've watched the Railscast about nested forms and followed the documentation at the Formtastic GitHub site, but I'm at a loss. Here's what I have.

The models:

class Decision < ActiveRecord::Base
  attr_accessible :title, :description, :user_id, :choices_attributes

  belongs_to :user

  has_many :choices, :dependent => :destroy

  accepts_nested_attributes_for :choices
end

class Choice < ActiveRecord::Base
  belongs_to :decision
end

In the Decisions_Controller:

def new
    @decision = Decision.new
    2.times do 
      @decision.choices.build
    end
  end

The decisions/new view:

<% semantic_form_for @decision do |form| %>
  <%= form.inputs :title, :description %>
  <%= form.inputs :summary, :for => :choice %> 
  <%= form.buttons %>
<% end %>

What I get is the form fields for title, description and one summary (for choice). How do I get the second choice to appear and get both fields to save?


Solution

  • Use :for => :choices instead of :for => :choice since that the name of the relation you want to reference.

    <%= semantic_form_for(@decision) do |form| %>
      <%= form.inputs :title, :description %>
      <%= form.inputs :summary, :for => :choices %>
      <%= form.buttons %>
    <% end %>