【问题标题】:Dynamically set dynamic finder in rails在rails中动态设置动态查找器
【发布时间】: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


    【解决方案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)
    

    【讨论】:

    • 该死!我显然需要更多的咖啡。谢谢!完美运行。
    猜你喜欢
    • 2017-04-26
    • 1970-01-01
    • 2012-12-24
    • 1970-01-01
    • 2011-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多