问题描述
所以基本上我尝试在父模型中创建一个记录几个小时。我显然在这里遗漏了一些东西。我的目标是在 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,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,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|
的表单视图看起来是正确的。
很确定您需要在 :id
中添加 guest_attributes: [:first_name,:last_name,:email]
例如:
params.require(:bill).permit(:special_req,guest_attributes: [:id,:first_name,:email])