-1

I have three models Book_Room, Invoice, and Bill. Invoice belongs to BookRoom, and has many bills. the error is unpermitted params error for :invoice is thrown when i try to create Book Room after ive clearly asked to accept nested params

class Invoice < ApplicationRecord
  belongs_to :book_room
  has_many :bills
  accepts_nested_attributes_for :bills
end

And BookRoom is meant to have only one invoice, but I used has_many because the fields_for form doesn't render when I use has_one.

class BookRoom < ApplicationRecord
  belongs_to :customer
  has_and_belongs_to_many :rooms
  has_many :invoices
  accepts_nested_attributes_for :invoices
end

Here is my create action for invoice controller:

def create
  @booking = BookRoom.find(params[:book_room_id])
  @invoice = @booking.invoice.new(invoice_params)

  if @invoice.save
    redirect_to @invoice, notice: 'Invoice was successfully created.'
  else
    render :new
  end
end

And here is my form, which is meant to create invoices and bills.

<%= f.fields_for :invoice do |i| %>
  <%= i.fields_for :bill do |b| %>
    <%= b.label :price %>
    <%= b.number_field :price %>
    <%= b.hidden_field :type, value: :deposit %>
  <% end %>
<% end %>

And finally, my book_room controller:

def create
  @book_room = @customer.book_rooms.new(book_room_params)

  if @book_room.save
    redirect_to @book_room, notice: 'Book room was successfully created.'
  else
    render :new
  end
end
def book_room_params
  params.require(:book_room).permit(:customer_id, :start_date, :end_date, :room_ids=>[], :invoices_attributes => [ :invoice_id, :bills_attributes => [:price, :type] ])
end

When I try to create a book room with bill records, it throws an error of unpermitted params invoice. If there is a way to get the form to render on has_one relationship, I will appreciate it.

Prince Abalogu
  • 385
  • 2
  • 4
  • 17

1 Answers1

0

Try switching to has_one :invoice association - fields_for can work with it, but you need to build association first with @book_room.build_invoice in BookRoomController#new controller action.

Then you can fix book_room_params - change invoices_attributes key to singular invoice_attributes.

Bartosz Pietraszko
  • 1,367
  • 9
  • 9
  • I have added this and still doesnt display the form.. but if i pluralise from f.fields :invoice to :invoices it shows the form.. but on :invoice it doesnt – Prince Abalogu Oct 12 '18 at 08:43