views:

41

answers:

1

Referencing question #2013421, I have the following RoR models:

class Game < ActiveRecord::Base
  has_many :piles
end

class Pile < ActiveRecord::Base
  belongs_to :game
end

For the sake of argument, suppose Game has an attribute name, and Pile has an attribute type, both string. There are precisely 10 piles per game.

I would like a single HTML form to create a new Game, similar to the one generated by ruby script\generate scaffold; that is like:

<h1>New game</h1>

<% form_for(@game) do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>
  <p>
    <%= f.submit 'Create' %>
  </p>
<% end %>

<%= link_to 'Back', games_path %>

How can I add fields to the form in order to read values for the Pile.type field for each of the 10 piles?

+3  A: 

You can do something like this:

model:

class Game < ActiveRecord::Base
  has_many :piles
  accepts_nested_attributes_for :piles
end

in your form:

 <% f.fields_for :piles do |pile_form| %>

   <%= pile_form.label :your_attribute %>
   <%= pile_form.text_field :your_attribute %>

 <% end %>

Consider that 'type' method-keyword-column is reserved by ActiveRecord to achieve polymorphic associations

see a good guide about nested forms in rails

makevoid
I see from the guide that accepts_nested_attributes_for is a Rails 2.3 feature. Sadly, my webserver is running on Debian using the apt-get packages, and so is only up to Rails 2.2.However, playing about I've managed to make the f.fields_for incantation work to provide me an interpretable hash, which is all I need.
Chris
If apt-get packages are behind, install the gem, it's equally simple to using apt-get.
EmFi
I don't own my webserver and my sysadmin is a sensible level of paranoid. While I'd be happy to install the gem, I respect his preference not to.
Chris