带有动态哈希的Rails update_attributes

use*_*201 2 ruby hash ruby-on-rails ruby-on-rails-4

我有一个Rails应用程序,在其中尝试用哈希中获取的属性更新模型。

我的代码是:

attr_hash = {"name"=>"cat_name"}

@category.update_attributes(attr_hash, :type => 'sample')
Run Code Online (Sandbox Code Playgroud)

这是我想要的类型将是固定的,并且attr哈希可以是基于表单提交的任何属性。但这给我一个错误。有任何想法吗?

sie*_*y22 6

attr_hash = {"name"=>"cat_name"}

@category.update_attributes(attr_hash.merge(type: "sample"))
Run Code Online (Sandbox Code Playgroud)

(因为update_attributes只需要一个哈希值)

说明:

目前,您正在传递此信息:

update_attributes({"name"=>"cat_name"}, {type: "sample"})

但是你想要这个:

update_attributes({"name"=>"cat_name", type: "sample"})

因此,您需要合并这两个哈希。