user4965201 user4965201 - 1 year ago 54
Ruby Question

Rails update_attributes with dynamic hash

I have a rails app in which I am trying to update a model with the attributes I am getting in the hash.

My code is:

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

@category.update_attributes(attr_hash, :type => 'sample')

Here is what I want that type will be fixed and the attr hash can be any attribute base on the form submit. But this gives me an error. Any ideas?

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

@category.update_attributes(attr_hash.merge(type: "sample"))

(because update_attributes takes only one hash)


Currently you're passing this:

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

but you want this:

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

So you need to merge these two hashes.