dimanche 2 août 2015

How to join elements in an array while still keep the double quotation?

I am reading the Rebuilding Rails book. In the little ORM chapter, it use sqlite3 gem to communicate with sqlite database. the my_table database structure

create table my_table (
 id INTEGER PRIMARY KEY,
 posted INTEGER,
 title VARCHAR(30),
 body VARCHAR(32000));

and the code that insert into my_table in .rb file is:

DB.execute <<-SQL
    INSERT INTO #{table} (#{keys.join ","})
    VALUES (#{vals.join ","});
    SQL
# vals=>["1", "It happend!", "It did!"]

But the sql statement it turn to will be this:

 "INSERT INTO my_table (posted,title,body)\n     VALUES (1,It happend!,It did!);\n"

It will raise a syntax error because of the miss of double quotation with "It happend!" and "It did!"

and i check the document finding that Array#join returns a string created by converting each element of the array to a string. Therefore the double quotation elements in the array will be converted to string and lose the double quotation. And cause that sql syntax error.

How to solve this?

Any help will be appreciate! Thanks!

Aucun commentaire:

Enregistrer un commentaire