Julinho da Adelaide Julinho da Adelaide - 6 months ago 19
Ruby Question

Ruby map function returning variables with brackets and quotes

I'm trying to use the

pipedrive-ruby
and sequel gems to retrieve and store data from a JSON hash to a db, but it always return values with quotes in every cell and square brackets at the beginning and end of the string. How can I solve this?

Code:

query_values = activities.map do |activity|
"#{activity['id']}"
end

query = "INSERT INTO pd_activities (id) VALUES (#{query_values})"
insert_ds = DB[query]
insert_ds.insert


Error when trying the insert into db:

/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sequel-4.34.0/lib/sequel/adapters/postgres.rb:186:in `async_exec': PG::SyntaxError: ERROR: syntax error at or near "[" (Sequel::DatabaseError)
LINE 1: INSERT INTO pd_activities (id) VALUES (["72943", "73532", "7...


Thanks

Answer

You're using string interpolation in an improper way to include values into an SQL statement.

This will work, instead:

query = "INSERT INTO pd_activities (id) VALUES ("#{query_values.join(', ')}")"

If the values in activities are integers, you can avoid string interpolation in the activities.map step. To do this, simply use this:

query_values = activities.map {|activity| activity['id'] }

If activities = [12, 34, 98, 142], this will produce:

"INSERT INTO pd_activities (id) VALUES (12, 34, 98, 142)"

However, if the values in activities are strings, you should do this instead:

query_values = activities.map {|activity| "'#{activity['id']}'" }

If activities = ["12", "34", "98", "142"], this will produce:

"INSERT INTO pd_activities (id) VALUES ('12', '34', '98', '142')"