Rails:执行sql查询并获取数组中的结果以在另一个语句中使用

时间:2017-10-06 23:20:58

标签: mysql ruby-on-rails

我有一个如下所示的查询:

    query= "
         SELECT
           (SELECT id FROM user_shift WHERE user_id = `u`.`id` AND `from_date` LIKE '#{days[0]}%') AS 'day_1'
          ,(SELECT id FROM user_shift WHERE user_id = `u`.`id` AND `from_date` LIKE '#{days[1]}%') AS 'day_2'
          ,(SELECT id FROM user_shift WHERE user_id = `u`.`id` AND `from_date` LIKE '#{days[2]}%') AS 'day_3'
          ,(SELECT id FROM user_shift WHERE user_id = `u`.`id` AND `from_date` LIKE '#{days[3]}%') AS 'day_4'
          ,(SELECT id FROM user_shift WHERE user_id = `u`.`id` AND `from_date` LIKE '#{days[4]}%') AS 'day_5'
          ,(SELECT id FROM user_shift WHERE user_id = `u`.`id` AND `from_date` LIKE '#{days[5]}%') AS 'day_6'
        FROM `user` AS `u`
        WHERE `u`.`id`= #{user_id}
    results = ActiveRecord::Base.connection.execute(query)
    shift_ids =  results.map {|key, value| [key, value.to_i ]}
    shift_ids.join(',')
results = ActiveRecord::Base.connection.execute(query)
shift_ids =  results.map {|key, value| [key, value.to_i ]}
shift_ids.join(',')

我为一个用户提供了这个:

SHIFT_IDS 25398,25399

我想在以下方面使用这些结果:

roster = UserShift.where("`id` IN (?)",shift_ids)

但似乎不是这样做的好方法。它返回:

SELECT `user_shift`.* FROM `user_shift` WHERE (`id` IN ('---\n- 25264\n- 25265\n'))

任何帮助都将不胜感激。

0 个答案:

没有答案