IN using an active record query database to create a list of integers

I am trying to replicate some SQL functions using ActiveRecord. My problem is related to my use of the ruby ​​join method (not to be confused with SQL join). Here is my code:

scope :stats_tips_given, lambda { |date|
  where("created_at >= ? AND tipper_id IN(?)",date, User.stats_users(date).collect(&:id).join(', '))
  }

However, the resulting SQL query has the following result: SELECT "tip_events".* FROM "tip_events" WHERE (created_at >= '2011-04-14' AND tipper_id IN('4, 5, 11, 17, 22, 48, 54, 65, 88, 103, 147, 151, 181, 182, 189, 195, 190, 196, 202, 226, 227, 231, 243, 245, 232, 225, 212, 217, 220, 263, 265, 273, 281, 282, 284, 286, 293, 271, 299, 300, 309, 310, 312, 318, 321, 308, 303, 297, 333, 346, 362, 368, 377, 386, 389, 392, 353, 398, 427, 420, 434, 418, 454, 456, 477, 484, 480, 453, 450, 452, 458, 497, 498, 503, 510, 511, 515, 522, 529, 537, 540, 508, 499, 524, 521, 502, 542, 546, 548, 557, 559, 571, 575, 576, 581, 587, 562, 580, 544, 567, 565, 573, 577, 597, 606, 619, 620, 640, 636, 607, 603, 600, 596, 656, 657, 668, 676, 683, 685, 662, 677, 669, 689, 678, 690, 694, 514, 206, 304, 601, 63, 495, 150, 344, 691, 490, 545, 634, 222, 288, 534, 630, 569, 323, 697, 489, 394, 568, 661, 672, 130, 381, 590, 205, 527, 474, 184, 622'))

This query would be perfect if it did not contain a single quote from a list of numbers. How to fix it?

+3
source share
1 answer

You create a string using join. Just pass it the actual array:

User.stats_users(date).collect(&:id)

Instead:

User.stats_users(date).collect(&:id).join(', ')
+7
source

All Articles