Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 373
user4965201 Avatar asked Feb 07 '23 14:02

user4965201


1 Answers

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

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

(because update_attributes takes only one hash)

Explanation:

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.

like image 171
siegy22 Avatar answered Feb 20 '23 10:02

siegy22