2013-05-29 49 views
0

我有以下型號一個Rails應用程序創建具有關係的新對象:沒有相關的編號

class Product < ActiveRecord::Base 
    has_many :stores, through: :product_store 

    attr_accessible :name, :global_uuid 
end 

class ProductStore < ActiveRecord::Base 
    attr_accessible :deleted, :product_id, :store_id, :global_uuid 

    belongs_to :product 
    belongs_to :store 
end 

由於該模型是一個移動應用程序的REST API,我遠程創建OBJETS,在設備,然後與此模型同步。發生這種情況時,可能會出現在爲Product設置id之前必須創建ProductStore。我知道我可以對API請求進行批處理並找到一些解決方法,但我已經解決了在移動應用中創建並同步的global_uuid屬性。

我想知道的是我怎麼能做出這種代碼在我的控制器:

def create 
    @product_store = ProductStore.new(params[:product_store]) 
    ... 
end 

意識到,這將是接收product_global_uuid參數,而不是一個product_id的參數,並把它適當地填充模型。

我想我可以覆蓋ProductStore#new但我不確定在做這件事時是否有任何分歧。

回答

1

覆蓋.new是一個危險的業務,你不想參與這樣做。我只想去:

class ProductStore < ActiveRecord::Base 
    attr_accessible :product_global_uuid 
    attr_accessor :product_global_uuid 

    belongs_to :product 
    before_validation :attach_product_using_global_uuid, on: :create 

    private 
    def attach_product_using_global_uuid 
    self.product = Product.find_by_global_uuid! @product_global_uuid 
    end 

end 

有這類人工attr_accessors那些只在模型製作採用的是一種雜亂,並且要避免在任何傳球不是模型的直接屬性,你正在儘可能創造。但正如你所說,有各種各樣的考慮需要平衡,而且這不是世界上最糟糕的事情。

+0

對我很好。我同意訪問者,但需要務實,並需要他們正確同步,這對這個項目更重要。 – pgb