0
我有一個表單,我需要創建兩個對象:sale
和organization
。這發生在sales_controller
內。如何在Rails中的一個創建控制器方法內創建兩個對象?
爲了簡潔起見,模型和它們的屬性是:
sale
amount (integer)
organization_id (uuid)
organization
name (string)
sale belongs_to organization
organization has_many sales
這是sales new
應該是什麼樣子。它有一個用於銷售的輸入,用戶將輸入該輸入,並且它還具有組織名稱的輸入,該用戶將輸入該組織名稱。提交後,用戶將創建新的銷售(並創建一個與該銷售相關的新組織)。
我想弄清楚什麼是sales_controller中create
方法的最佳實踐。
def create
@sale = Sale.new(sale_params) #assume sale_params permits organization_id and amount
@organization = Organization.create(params[:name])
#@sale.organization_id = @organization.id
if @sale.save
render json: @sale
else
render json: sale, status: :unprocessable_entity
end
end
@organization = Organization.create(...)
感覺不對。有沒有辦法做到多個對象提交「Rails」?
一篇舊文章,但以下內容應該有所幫助:https://webuild.envato.com/blog/creating-form-objects-with-activemodel-and-virtus/ 你實際上並不需要Virtus,但文章會給你包括驗證等的要點 – dmcnally