我应该如何在使用 'first_or_create' 时合并散列

How should I merge hash while using 'first_or_create'

我有这个哈希,它是动态构建的:

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' 返回),它将不会被更新...虽然那将是一个不错的选择并且欢迎任何相关建议,但是 table 刚刚删除并重新创建,所以这不是问题。

我错过了什么?

我也尝试使用 to_sym,结果是:

additional_values = {:grouping_id=>1}

...以防出现一些我不知道的怪事...没有什么不同

问题是Hash#merge returns a new hash and then you aren't doing anything with that hash, you're just throwing it away. I would also suggest sticking to using the ActiveRecord methods for updating attributes, instead of trying to manipulate the underlying hash, such as using assign_attributes or, if you want to save the record update. Though, you may find the create_with, which can be used with find_or_create_by,在这里有用:

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

我在最近的 rails 版本中找不到任何我喜欢的 first_or_create 的文档(如果有的话),但是如果你喜欢它而不是 find_or_create_by,那么如果我们看看 Rails 3 documentation for first_or_create,你应该可以不用 create_with:

model.where(name: 'test').first_or_create(additional_attributes)