2012-07-15 34 views
0

無論何時創建實體A,我都需要創建一個新實體B。爲此,我嘗試在a_controllerA.create方法內添加B.create的調用。然而,這給出了一個錯誤:使用一個controller.create創建2個不同實體

Missing template a/create 

所以我的問題是:如何創建從A.create控制器實體B

回答

2

這樣的事情?

def create 
    @A = A.new(params[:a]) 
    @B = B.new(params[:b]) 

    respond_to do |format| 
    if @A.save && @B.save 
     format.html { redirect_to @A, :notice => 'A was successfully created.' }   
    else 
     # render new with validation errors 
     format.html { render :action => "new" }   
    end 
    end 
end 

但如果你的對象是「相關」,即的has_many或belongs_to的,那麼你可能要像

# project has_many tasks 
def create 
    @project = Project.new(params[:project]) 
    @project.tasks.new(params[:task]) 
    if @project.save # this should save both objects and in the same transaction 
    .... 
end 

和第三選擇是使用accepts_nested_attributes_for - 在這裏閱讀更多:http://currentricity.wordpress.com/2011/09/04/the-definitive-guide-to-accepts_nested_attributes_for-a-model-in-rails-3/

+0

東西像那樣!謝謝! – Michael 2012-07-15 20:10:58

相關問題