Rails: Nested attributes not populating with fields_for

Viewed 28

I'm trying to create a record (cars) from another model at the same time a create a new resident. Here is my code. What I'm doing wrong here?

Resident controller

def new
  @resident = Resident.new
  @resident.cars.build
end

def create
  @resident = Resident.new
  @resident.cars.build
end

Resident model

class Resident < ApplicationRecord
  belongs_to :building
  has_many :cars
  accepts_nested_attributes_for :cars
end

/residents/new.html.erb

...
<%= fields_for :cars do |f| %>
  <%= f.text_field :model %>
  <%= f.text_field :brand %>
  <%= f.text_field :color %>
  <%= f.text_field :plate %>
<% end %>

But when I try to create a new record the values are coming null. Here is the log.

Parameters: {"authenticity_token"=>"[FILTERED]", "resident"=>{"building_id"=>"1", "apartment"=>"123", "name"=>"Joaquim 2", "email"=>"uol@gmail.com", "rg"=>"123123", "cpf"=>"123123", "workphone"=>"121288", "homephone"=>"93278340", "mobile"=>"1283918", "tipo"=>"Locatario", "birthdate(1i)"=>"2022", "birthdate(2i)"=>"9", "birthdate(3i)"=>"19"}, "cars"=>{"model"=>"fusca", "brand"=>"volks", "color"=>"preto", "plate"=>"KIO12312"}, "commit"=>"Cadastrar"} User Load (0.4ms) SELECT users.* FROM users WHERE users.id = 4 LIMIT 1 ↳ app/helpers/sessions_helper.rb:10:in current_user' TRANSACTION (0.1ms) BEGIN ↳ app/controllers/residents_controller.rb:40:in create' Building Load (0.3ms) SELECT buildings.* FROM buildings WHERE buildings.id = 1 LIMIT 1 ↳ app/controllers/residents_controller.rb:40:in create' Resident Create (0.6ms) INSERT INTO residents (name, rg, cpf, workphone, homephone, created_at, updated_at, building_id, local, birthdate, mobile, tipo, apartment, email) VALUES ('Joaquim 2', '123123', '123123', '121288', '93278340', '2022-09-19 15:15:22.289720', '2022-09-19 15:15:22.289720', 1, NULL, '2022-09-19', '1283918', 'Locatario', '123', 'uol@gmail.com') ↳ app/controllers/residents_controller.rb:40:in create' Car Create (1.2ms) INSERT INTO cars (model, color, plate, created_at, updated_at, resident_id, brand) VALUES (NULL, NULL, NULL, '2022-09-19 15:15:22.293364', '2022-09-19 15:15:22.293364', 11, NULL) ↳ app/controllers/residents_controller.rb:40:in `create' TRANSACTION (0.5ms) COMMIT

Extra question =] How can I create more cars? Is simple like repeat the form?

1 Answers

fields_for has no reference to the parent model.

Example:

form_with model: @resident | form |


form.fields_for :cars do | f |

…

end

end

Related