【发布时间】:2012-04-04 15:32:02
【问题描述】:
我有 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
【问题讨论】:
标签: ruby-on-rails activerecord ruby-on-rails-3.1