K
K
Kirill Popolov2014-06-10 06:59:29
ruby
Kirill Popolov, 2014-06-10 06:59:29

How to build a form with some number of identical fields in RoR?

There is a task:
Display a form with contacts on the page - for each contact there are three fields (name, phone number, weight) + a hidden field with id.
In accordance with the rails guide, I do a form builder for each contact:

- @contacts.each do |contact|
  - fields_for contact, index: contact.id do |contact_form|
    %tr                
      %td
        = contact_form.hidden_field_tag(:id, contact.id, class: 'form-control')
        = contact_form.text_field_tag(:phone, contact.phone, class: 'form-control')
      %td
        = contact_form.text_field_tag(:name, contact.name, class: 'form-control')
      %td
        = contact_form.text_field_tag(:weight, contact.weight, class: 'form-control')

But I get undefined method `hidden_field_tag' for #
at the same time, if you do not use fields_for, then the form is built, but, of course, only the last group of fields is sent.
I can't figure out where I went wrong.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kirill Popolov, 2014-06-10
@ezhikov

I used the wrong method. Hidden_field should have been used instead of hidden_field_tag ​​. As always, carelessness ruined me.
As a result, the code turned out like this:

- @contacts.each do |contact|
  = fields_for "contact[#{contact.id}]" do |contact_form|
    %tr                
      %td
        = contact_form.hidden_field(:id, :value => contact.id)
        = contact_form.text_field(:phone, :value => contact.phone, :class => "form-control")
      %td
        = contact_form.text_field(:name, :value => contact.name, :class => "form-control")
      %td
        = contact_form.text_field(:weight, :value => contact.weight, :class => "form-control")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question