我有三个模型Book_Room
,Invoice
和Bill
。 Invoice
属于BookRoom
,有很多账单。错误是不允许的参数错误:在我明确要求接受嵌套参数后,当我尝试创建书房时,抛出了发票错误
class Invoice < ApplicationRecord
belongs_to :book_room
has_many :bills
accepts_nested_attributes_for :bills
end
BookRoom
只能有一张发票,但是我使用has_many
是因为当我使用fields_for
时has_one
表单不呈现。
class BookRoom < ApplicationRecord
belongs_to :customer
has_and_belongs_to_many :rooms
has_many :invoices
accepts_nested_attributes_for :invoices
end
这是我对create
控制器的invoice
动作:
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
这是我的表单,用于创建发票和票据。
<%= 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 %>
最后,我的book_room
控制器:
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
当我尝试创建带有账单记录的书房时,会引发错误的参数发票错误。如果有一种方法可以使表单呈现为has_one
关系,我将不胜感激。
答案 0 :(得分:0)
尝试切换到has_one :invoice
关联-fields_for
可以使用它,但是您需要先在@book_room.build_invoice
控制器操作中使用BookRoomController#new
建立关联。
然后,您可以修复book_room_params
-将invoices_attributes
键更改为单数invoice_attributes
。