2012-10-19 41 views
3

我有兩個應用程序,應用1和應用2。 App1將JSON有效內容發佈到包含父對象和子對象數據的App2。如果父對象應用2已經存在,那麼我們更新父記錄,如果事情發生了變化,並創建應用2子記錄。如果父對象不存在應用2,我們首先需要創建它,然後創建子對象和兩個關聯。現在我正在這樣做:什麼是創建一個POST父和子對象的最佳方式?

class ChildController 
    def create 
    @child = Child.find_or_initialize_by_some_id(params[:child][:some_id]) 
    @child.parent = Parent.create_or_update(params[:parent]) 

    if @child.update_attributes(params[:child]) 
     do_something 
    else 
     render :json => @child.errors, :status => 500 
    end 
    end 
end 

東西感覺很髒關於創建/更新父母那樣的。有沒有更好的方法來解決這個問題?謝謝!

回答

3

作爲一個起點,你需要創建模型中的關聯,然後包括你的父母accepts_nested_attributes_for

隨着你的模型創建的關聯,你應該能夠操縱的關係很容易,因爲你自動獲得的預期管理關係方法的主機。例如,你的父/子模型可能是這個樣子:

在你父模型:

class Parent < ActiveRecord::Base 
    has_many :children 
    accepts_nested_attributes_for :children 

在孩子模式:

class Child < ActiveRecord::Base 
    belongs_to :parent 

然後,你應該能夠建立

def new 
    @parent = Parent.children.build 
end 

def create 
    @parent = Parent.children.build(params[:parent]) 
end 

的nested_attributes屬性將然後允許:在您的控制器這樣的協會你通過操作Parent來更新Child的屬性。

下面是關於這個專題的Rails的API:http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

相關問題