代码之家  ›  专栏  ›  技术社区  ›  webaholik Unixmonkey

如何在使用“first_or_create”时合并散列

  •  3
  • webaholik Unixmonkey  · 技术社区  · 8 年前

    我有这个散列,它是动态构建的:

    additional_values = {"grouping_id"=>1}
    

    我想在创建后通过 first_or_create 以下内容:

    result = model.where(name: 'test').first_or_create do |record|
      # I'm trying to merge any record attributes that exist in my hash:
      record.attributes.merge(additional_values)
      # This works, but it sucks:
      # record.grouping_id = data['grouping_id'] if model.name == 'Grouping'
    end
    #Not working:
    #result.attributes>>{"id"=>1, "name"=>"Test", "grouping_id"=>nil}
    

    我知道,如果记录已经存在(通过“first”返回),它将不会被更新……尽管这是一个不错的选择,并且欢迎对其提出任何建议,但是表只是被删除并重新创建了,所以这不是问题所在。

    我错过了什么?

    我也试过用 to_sym ,结果是:

    additional_values = {:grouping_id=>1}
    

    ……以防万一我不知道有什么怪事……没什么区别

    1 回复  |  直到 8 年前
        1
  •  3
  •   Simple Lime    8 年前

    问题是 Hash#merge 返回一个新的散列,然后你不做任何事情与散列,你只是扔掉它。我还建议坚持使用activerecord方法来更新属性,而不是尝试操作底层散列,例如使用 assign_attributes 或者,如果你想保存记录 update 是的。不过,你可能会发现 create_with ,可与 find_or_create_by ,此处有用:

    model.create_with(additional_values).find_or_create_by(name: 'test')
    

    我找不到任何我喜欢的文档(如果有的话) first_or_create 在最近的rails版本中,但是如果您喜欢 查找或创建 ,那么如果我们看看 Rails 3 documentation for first_or_create ,你应该可以处理掉 创建 以下内容:

    model.where(name: 'test').first_or_create(additional_attributes)
    
    推荐文章