Ruby on Rails: How to collect values ​​for child tables from a form?

Referring to question No. 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 argument, suppose that it Gamehas an attribute name, and Pilehas an attribute type, both string. There are exactly 10 piles in the game.

I would like one HTML form to create a new Game, similar to the one that was created ruby script\generate scaffold; What is it 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 to add fields to a form for reading field values Pile.typefor each of 10 piles?

0
source share
1 answer

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 %>

, type-keyword-column ActiveRecord

.

+3

Source: https://habr.com/ru/post/1729416/


All Articles