1
在我的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
感謝您的幫助。
你可以嘗試在'@invoice = ...'行後面加上一個'binding.pry'(如果你沒有它的話,添加gem'pry')。然後,觀看invoice_params中的內容,並執行必要的操作以使其工作:) – Poilon