Nested form in Rails. Can't create and associate a parent

90 Views Asked by At

So basically I tried to create a record in a parent model for few hours. I'm clearly missing something here. My goal is to create a bill in the Bills table and, with basic guest info in the same form, create another record in the Guests table. View my code down below (sorry if the format is not adequate, it's my first post on stackoverflow)

bill.rb

class Bill < ApplicationRecord
  belongs_to :guest, inverse_of: :bills
  accepts_nested_attributes_for :guest

guest.rb

class Guest < ApplicationRecord    
  has_many :bills, inverse_of: :guest

bills_controller.rb

def new
    @bill = Bill.new
    @bill.build_guest

...

def create
  @bill = Bill.new(bill_params)

if @bill.save

...

def bill_params
    params.require(:bill).permit(:special_req, guest_attributes: [:first_name, :last_name, :email])

_form.html.haml

=form_with(model: [:admin, @bill], local: true) do |form| 
    .form-group.row
        .col-3
            = form.label :room_id, class: "col-form-label text-dark"
        .col-9
            = form.collection_select :room_id, @availabilities, :id, :door_no, class: "col-form-label text-dark"
    = form.fields_for :guests do |guest_form|
        .form-group.row
            .col-3
                = guest_form.label :first_name, class: "col-form-label text-dark"
            .col-9
                = guest_form.text_field :first_name, class: "form-control rounded", placeholder: "Tom"
        .form-group.row
            .col-3
                = guest_form.label :last_name, class: "col-form-label text-dark"
            .col-9
                = guest_form.text_field :last_name, class: "form-control rounded", placeholder: "Jedusor"
        .form-group.row.margin-bottom
            .col-3
                = guest_form.label :email, class: "col-form-label text-dark"
            .col-9
                = guest_form.text_field :email, class: "form-control rounded", placeholder: "[email protected]"
    .form-group.row.align-items-center
        .col-6
            = link_to "[ Cancel operation ]", admin_bills_path, class: "text-info"
        .col-6.text-right
            = form.submit "Send", class: "btn btn-outline-success btn-lg"

A guest can have multiple bills, but a bill can only have one guest. Account registration is not a question for now, it's just there to serve some record purposes. This is just an exercise, so there is no real world deployment. Still, I need to go through that step.

1

There are 1 best solutions below

2
Sarah Marie On

The form view using form.fields_for :guests do |guest_form| looks correct.

Pretty sure you need to add :id in guest_attributes: [:first_name, :last_name, :email]

For Example:

params.require(:bill).permit(:special_req, guest_attributes: [:id, :first_name, :last_name, :email])