我有一个 Rails 应用程序,我在其中尝试使用我在哈希中获得的属性更新模型。
我的代码是:
attr_hash = {"name"=>"cat_name"}
@category.update_attributes(attr_hash, :type => 'sample')
这就是我想要的类型将被修复并且 attr 哈希可以是基于表单提交的任何属性。但这给了我一个错误。有什么想法吗?
最佳答案
attr_hash = {"name"=>"cat_name"}
@category.update_attributes(attr_hash.merge(type: "sample"))
(因为update_attributes
只需要一个散列)
解释:
目前你正在传递这个:
update_attributes({"name"=>"cat_name"}, {type: "sample"})
但是你想要这个:
update_attributes({"name"=>"cat_name", type: "sample"})
所以你需要合并这两个哈希。
关于ruby-on-rails - 具有动态哈希的 Rails update_attributes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38304422/