0

I have an instance variable with a hash as one of its properties. Assume that I don't want to use associations. I want to add to this hash and I'm currently doing it this way.

# dog.owners = { "Brad": "bar", "Matt": "foo"}
hash = dog.owners
hash["David"] = "foose"
dog.update(owners: hash)

Is there a way to do in a one-liner?

2 Answers 2

2

dog.update owners: dog.owners.merge( David: "foose" )

Update

Please note that the comment in your question shows the hash keys being symbols, ie. in { "Brad": "bar" } the presence of the : will make "Brad" into the symbol :Brad in the resulting hash.

This is important because later in your question you show hash["David"] = "foose" - that's adding a new element to the hash with a string key "David"!

This is important because "David" != :David so, for example:

[11] pry(main)> x = { "David": "symbol" }
=> {:David=>"symbol"}
[12] pry(main)> x["David"] = "string"
=> "string"
[13] pry(main)> x               
=> {:David=>"symbol", "David"=>"string"}

So, be careful there.

Second Update :)

All that being said, if this field is just coming out of a JSON(B) field from a DB or something then actually your keys might all be strings, in which case you should show your hash with => not : (but maybe you were showing the raw JSON).

Sign up to request clarification or add additional context in comments.

Comments

0

Look at using serialize. This lets ActiveRecord be a bit smarter about dealing with objects.

class Dog < ApplicationRecord
    serialize :owners
end

...

dog = Dog.first
dog.owners["David"] = "foose"
dog.changes
dog.save

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.