Sylar Sylar - 6 months ago 31
Ruby Question

Update Model with column objects

I do hope the title is correct. Using a Rails 5 project with PostgreSQL and Ruby 2.3.1.

I have enabled hstore in my app. I do not know the correct way to update a table column with an object data. Make sense?

# There will be only two arrays:
cars = ["honda", "bmw"]
rate = [1, 2] do |c,r|
Foo.find(1).update_attributes(bar: {c => r})
# Foo.find(1).bar = {"bmw" => 2}

I expect:

# Foo.find(1).bar = {"honda" => "1", "bmw" => 2}

How to get the two values into

I was trying to fit one of my previous questions into this but not sure where to start.


You can create a hash from the array

 a =
 Foo.find(1).update_attributes(bar: Hash[a]) 

or if you need some enumerator { |x| Foo.find(1).update_attributes(bar: Hash[x]) }