我有 rake 任务从几个不同的来源和格式导入数千条记录,我希望在解析后干掉我的代码,他们目前使用 find_or_initialize_by_* 动态查找器创建或更新模型记录。
本质上,我希望能够传入 find_or_initialize_by_* 方法的 * 部分。
这是一些 sudo 代码来尝试解释我想要实现的目标。
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
然后我会在产品导入中使用类似这样的东西从 rake 任务中调用...
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