在我的Ruby on Rails应用程序中,我有一个像这样设置的多态关联:
class Invoice < ApplicationRecord
belongs_to :invoiceable, polymorphic: true
end
class Person < ApplicationRecord
has_many :invoices, as: :invoiceable
end
class Company < ApplicationRecord
has_many :invoices, as: :invoiceable
end
我的用户应该能够选择新发票是与个人或公司相关联。怎么办呢?
我认为必须是这样的:
<%= f.select :invoiceable, current_user.people.options + current_user.companies.options %>
这会正确填充表单,但在用户保存发票时,它不会保存到invoiceable_id
和invoiceable_type
数据库字段。
这是我的InvoicesController操作:
def create
@invoice = current_user.invoices.build(invoice_params)
if @invoice.save
flash[:success] = "Invoice saved."
redirect_to invoice_path(@invoice)
else
render :new
end
end
感谢您的帮助。