1} 我想在通过 first_or_create 创建后将其与此记录对象合并: result =-6ren">
gpt4 book ai didi

ruby - 使用 'first_or_create' 时应该如何合并哈希

转载 作者:数据小太阳 更新时间:2023-10-29 07:58:18 26 4
gpt4 key购买 nike

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

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}

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

最佳答案

问题是Hash#merge返回一个新的散列,然后你没有对那个散列做任何事情,你只是把它扔掉了。我还建议坚持使用 ActiveRecord 方法来更新属性,而不是尝试操纵底层哈希,例如使用 assign_attributes或者,如果您想保存记录 update .不过,您可能会发现 create_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)

关于ruby - 使用 'first_or_create' 时应该如何合并哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51028361/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com