以祖父母形式创建子孙记录的记录时出现不允许的参数错误

时间:2018-10-12 08:14:44

标签: ruby-on-rails model-associations

我有三个模型Book_RoomInvoiceBillInvoice属于BookRoom,有很多账单。错误是不允许的参数错误:在我明确要求接受嵌套参数后,当我尝试创建书房时,抛出了发票错误

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

BookRoom只能有一张发票,但是我使用has_many是因为当我使用fields_forhas_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关系,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

尝试切换到has_one :invoice关联-fields_for可以使用它,但是您需要先在@book_room.build_invoice控制器操作中使用BookRoomController#new建立关联。

然后,您可以修复book_room_params-将invoices_attributes键更改为单数invoice_attributes