所以基本上我尝试在父模型中创建记录几个小时。我显然漏掉了什么。我的目标是在Bills表中创建一个账单,并使用相同形式的基本客人信息在Guests表中创建另一个记录。查看下面我的代码(抱歉,如果格式不够,这是我在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: "nagano@inn.com"
.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"
一个客人可以有多个账单,但一个账单只能有一个客人。帐户注册现在不是一个问题,它只是用于一些记录目的。这只是一个练习,因此没有实际的部署。但是,我仍然需要完成这一步。
使用form.fields_for :guests do |guest_form|
的表单视图看起来正确。
很确定你需要在guest_attributes: [:first_name, :last_name, :email]
中添加:id
例如:
params.require(:bill).permit(:special_req, guest_attributes: [:id, :first_name, :last_name, :email])