Question

I have a complex model backed form and want to include multiple objects into my params.

My setup:

Network.rb

class Network < ActiveRecord::Base                 # t.string "name"
  has_many :trackings
  has_many :installations, through: :trackings  
end

Installation.rb

class Installation < ActiveRecord::Base            # t.string "name"
  has_many :trackings
  has_many :networks, through: :trackings
end

Tracking.rb

class Tracking < ActiveRecord::Base                # t.string "code
  belongs_to :network                              # t.integer "network_id",
  belongs_to :installation                         # t.integer "installation_id
end

When I create a new Tracking-Object, I want to render each Network in the database and add a textfield for :code mockup new tracking

My form:

= form_for [:admin, @tracking] do |f|

  = f.select :installation_id, options_for_select(Installation.all.map { |i| [i.name, i.id] }), prompt: "Select an Installation"

  - Network.all.each do |network|
    = f.text_field :code
  = f.submit

Currently all text fields get rendered but when I submit, only the last input of the last text field gets into my params. How can I include ALL of them?

For non model-backed form I found this, but it's not working for my form:

= text_field_tag "tracking[][code]"
Was it helpful?

Solution

The problem is that all form fields in each iteration of network have the same name so they're all mapped to the same position on your input hash... which is why you only see the last entry.

If you do...

=text_field_tag "admin[][code[][#{network_id}]]"

... you'll get code returned as a hash with network_id as the key, and user input as the value. So you'll get separate values that you can manipulate.

OTHER TIPS

The problem is that when a view gets rendered, it all gets translated into a format suitable for an HTML PUT, which does not support arrays. You'll need to assign a different name to each code field, perhaps appending the array index to the end of each one after a delimiter (:code-2 for example). Each value will then have it's own parameter. When the form gets posted, you can split the names using the delimiter to find those that start with post, and get the array index back so you can assign it to the array again.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top