Shelvacu
Shelvacu

Reputation: 4362

How to write form for multiple children of object in rails

Say I have these classes

class Company
  has_many :workers
end

class Worker
  belongs_to :company
end

I want a page where the company and each worker can be modified. My attempt was something like this:

= form_for @company do |f|
  = f.text_input :name
  -# etc..
  - @company.workers.each do |worker|
    = f.fields_for worker do |fw|
      = f.text_input :name
      = f.text_input :title

However, the fields for the worker have names like company[worker][title] which doesn't include an identifier for the worker, so all the title fields for each worker have the same name.

What is the proper way to create a form for multiple objects belonging to a single object?

Upvotes: 1

Views: 560

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

You can make your code more succinct, using the following (One-to-Many):

= form_for @company do |f|
  = f.text_input :name
  -# etc..
    = f.fields_for :workers, @company.workers do |fw|
      = fw.text_input :name
      = fw.text_input :title

Upvotes: 1

yez
yez

Reputation: 2378

As @max pointed out, you want to use fields_for. Specifically, you want to use the one-to-many implementation.

This means your model will need to accept nested attributes

class Company
  has_many :workers
  accepts_nested_attributes_for :workers
end

And your form will be nested with a fields_for block, which you have but you are using the wrong block argument. Instead of f you want to use fw

= form_for @company do |f|
  = f.text_input :name
  -# etc..
  - @company.workers.each do |worker|
    = f.fields_for :workers, worker do |fw|
      = fw.text_input :name
      = fw.text_input :title

Upvotes: 2

Related Questions