2012-04-04 33 views
0

我rake任務從幾個不同的源和格式導入上千條記錄,我期待解析,在那裏他們目前使用find_or_initialize_by_ *動態查找創建或更新型號記錄後幹起來我的代碼。在軌動態設置動態取景器

從本質上講,我希望能夠在find_or_initialize_by_ *方法*部分通過。

下面是一些須藤代碼,試圖解釋,我想達到的目標。

def create_or_update_record(*args) 
    model = args[0].classify.constantize 
    identifier = args[1] 
    attributes = args.extract_options! 

    XXX = identifier 

    record = model.find_or_initialize_by_XXX(identifier.to_sym => @identifier_value) 

    attributes.each do |attribute| 
    #set value of attribute here 
    end 

    record.save 
end 

其中我會再從耙任務,在產品導入像這樣打電話......

create_or_update_record('Product', 'product_id',{ 
    "product_id" => "1", 
    "product_price" => "2.99" 
    }) 

和像這樣的類別進口...

create_or_update_record('Category', 'category_id',{ 
    "category_id" => "1", 
    "category_name" => "Gloves" 
    }) 

我猜我需要重寫和擴展底層的method_missing。從我發現的這篇博客文章看起來相當複雜。 http://blog.hasmanythrough.com/2006/8/13/how-dynamic-finders-work

回答

1

像這樣的工作:

要創建

#record = model.find_or_initialize_by_XXX(identifier.to_sym => @identifier_value) 

我們要派動態取景器的對象,並使用現有的方法缺少

identifier = "XXX" 
record = model.send("find_or_initialize_by_#{identifier}", identifier.to_sym => @identifier_value) 
+0

黨!我顯然需要更多的咖啡。謝謝!完美工作。 – 2012-04-04 15:47:35