radical_edo
radical_edo

Reputation: 994

rails 3 fields_for nested forms multiple records

Maybe someone here will help me.

I've got the following model vehicle.rb:

class Vehicle < ActiveRecord::Base
  attr_accessible :parameters_attributes
  has_many :parameters, dependent: :destroy
  accepts_nested_attributes_for :parameters, reject_if: lambda {
  |attrs| attrs.all? {
    |tag, value|
      value.is_a?(Integer)
      tag.blank?
    }
  }
end

vehicles_controller.rb

def new
  @vehicle = Vehicle.new
end

and in my view new.html.haml:

= form_for [:admin, setup(@vehicle)], html: { multipart: true } do |f|
  %fieldset{ data: { hook: "new_vehicle" } }
    %legend{ align: "center" }
      = t(:new_vehicle)
  = render partial: 'shared_vehicle_fields', locals: { f: f }
  = f.field_container :size do
  = f.label :size
  %span.required *
  %br/
  = f.select :size, [t(:please_select) , "small", "medium", "large"], class: 'require'
  .parameter_fields
  %div.small_vehicle_parameters
    = f.fields_for :parameters do |pf|
      = render 'parameter_fields', f: pf, text: 'A1'
    = f.fields_for :parameters do |pf|
      = render 'parameter_fields', f: pf, text: 'A2'
  %div.medium_vehicle_parameters
  %div.large_vehicle_parameters
  %br/
  = f.submit t(:submit)

the setup(@vehicle) is the following helper:

def setup(vehicle)
  returning(vehicle) do |car|
    car.parameters.build if car.parameters.blank?
  end
end

the partial parameter_fields is nothing special, but I'll show it just in case:

= f.label :tag, text
= f.text_field :value, size: 4
= f.hidden_field :tag, { value: text }
%br/

Now, the problem is this:

When I type in the correct values in any of the fields of the form everything is fine. It creates the models and records as I want them. But, if any of the validation doesn't pass the form is rendered again with error message. However, the parameter text_fields are multiplied. I get 2 fields_for with tag A1 and 2 fields with tag A2. If I had 3 fields_for, then there would be 3 of each and so on.

I know how many records I need to create in table (depends on vehicle size), if that helps.

Help, anyone?

Upvotes: 0

Views: 1153

Answers (1)

radical_edo
radical_edo

Reputation: 994

For anyone who might run into a similar problem and is stunned as I was....

What happen was, after the failed validation the @vehicle.parameters had a list of records he wanted to create, which, in turn, made render that amount of text_fields for each fields_for there was on the page. That's how this is made, Ruby on Rails is smart like that. This comes handy when editing the form. He automatically renders the 'right' amount of fields. At least that's how I understood the problem.

Anyways, I've added the following line in the create action if the save was unsuccessful.

@vehicle.parameters = []

Upvotes: 1

Related Questions