将SQL转换为ActiveRecord查询

时间:2014-03-24 11:07:47

标签: mysql sql ruby-on-rails activerecord

如何将以下SQL查询转换为ActiveRecord Query以减轻SQL注入?

jacket_colors ||= [2,21,25,20]
jacket_types = JacketType.find_by_sql(<<-SQL)
  SELECT j2.*, t1.no_count
   FROM jeans j2
   INNER JOIN (
     SELECT
     j1.jean_id AS jean_id,
     COUNT(j1.id) AS no_count
     FROM tracks t
     INNER JOIN jacket_types j1 ON j1.track_id = t.id
     INNER JOIN jeans j2 ON j2.id = j1.jean_id
     WHERE t.status = 0
       AND j1.status IN (#{jacket_colors})
       AND t.type != 'TrekkingTrack'
     GROUP BY j1.jean_id
     HAVING COUNT(j1.id) > 0
   ) t1 ON t1.jean_id = j2.id
 SQL

jacket_types 因用户输入而异。

我尝试了以下操作,但这不起作用并产生错误的SQL。

jacket_colors ||= [2,21,25,20]

Jean.joins(:jacket_types, :track)
.select('jeans.jacket_types_id AS jacket_types_id, COUNT(jeans.id) AS no_count').
where('jeans.status IN (?) AND tracks.status = ? AND tracks.type != ?', jacket_colors, 0, 'TrekkingTrack')
.group('jeans.jacket_types_id')
.having('COUNT(jeans.id) > ?', 0)
.select('jacket_types.*, tracks.no_count').explain

1 个答案:

答案 0 :(得分:2)

请尝试一下,我认为它会起作用。

Rails查询版本:

jacket_colors ||= [2,21,25,20]

Jean.joins(:jacket_types => :track)
 .where('jeans.status IN (?) AND tracks.status = ? AND tracks.type != ?',
 jacket_colors, 0, 'TrekkingTrack').group('jeans.jacket_types_id')
.select('jacket_types.column1, jacket_types.column2, ....., 
 count(jacket_types) no_count').having("no_count > 0")

jacket_colors ||= [2,21,25,20]
jacket_types = JacketType.find_by_sql(<<-SQL)
  SELECT j2.*, t1.no_count
  FROM jeans j2
    INNER JOIN (
      SELECT
      j1.jean_id AS jean_id,
      COUNT(j1.id) AS no_count
      FROM tracks t
        INNER JOIN jacket_types j1 ON j1.track_id = t.id
        INNER JOIN jeans j2 ON j2.id = j1.jean_id
        WHERE t.status = 0
        AND j1.status IN (#{jacket_colors})
        AND t.type != 'TrekkingTrack'
        GROUP BY j1.jean_id
        HAVING COUNT(j1.id) > 0
   ) t1 ON t1.jean_id = j2.id
 SQL