2017-04-19 36 views
0

我有一個表單,我需要創建兩個對象:saleorganization。這發生在sales_controller內。如何在Rails中的一個創建控制器方法內創建兩個對象?

爲了簡潔起見,模型和它們的屬性是:

sale 
    amount (integer) 
    organization_id (uuid) 

organization 
    name (string) 

sale belongs_to organization 
organization has_many sales 

Sales Form

這是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」?

+0

一篇舊文章,但以下內容應該有所幫助:https://webuild.envato.com/blog/creating-form-objects-with-activemodel-and-virtus/ 你實際上並不需要Virtus,但文章會給你包括驗證等的要點 – dmcnally

回答

1

既然你可能已經在以前的銷售創造了一個組織,你可以使用:

@organization = Organization.find_or_create_by(name: params[:name])

然後由sale.organization_id關聯繼續。您還需要對Organization.name具有唯一性約束。

相關問題