· 10 years ago · Sep 19, 2016, 11:56 PM
1def self.where_in(field, ids)
2 tmp_table = "tmp_table_#{SecureRandom.uuid.gsub('-', '_')}"
3 begin
4 # Create temporary table with one column
5 connection.execute("CREATE TEMPORARY TABLE #{tmp_table} (param INT NOT NULL PRIMARY KEY) ENGINE=Memory")
6
7 # Insert ids into the table (doesn't have to be ids)
8 vals = ids.map{|i| "(#{i})"}.join(", ")
9 connection.execute("INSERT INTO #{tmp_table} (param) VALUES #{vals};")
10
11 # Return the join relation which is the same as WHERE IN (...)
12 return self.joins("INNER JOIN #{tmp_table} on #{field} = #{tmp_table}.param").all
13 ensure
14 # Drop table after we're done...this is the problem
15 connection.execute("DROP TEMPORARY TABLE IF EXISTS #{tmp_table}")
16 end
17end