Julinho da Adelaide Julinho da Adelaide - 10 months ago 41
Ruby Question

Map function returning variables with brackets and quotes

I'm trying to use the

and Sequel gems to retrieve and store data from a JSON hash to a database, but it always returns values with quotes in every cell and square brackets at the beginning and end of the string. How can I solve this?


query_values = activities.map do |activity|

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

This is the error when trying to insert into the database:

/.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...


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')"