mysql - Convert SQL to ActiveRecord Query -


how can convert following sql query activerecord query in order mitigate sql injection?

jacket_colors ||= [2,21,25,20] jacket_types = jackettype.find_by_sql(<<-sql)   select j2.*, t1.no_count    jeans j2    inner join (      select      j1.jean_id jean_id,      count(j1.id) no_count      tracks t      inner join jacket_types j1 on j1.track_id = t.id      inner join jeans j2 on j2.id = j1.jean_id      t.status = 0        , j1.status in (#{jacket_colors})        , t.type != 'trekkingtrack'      group j1.jean_id      having count(j1.id) > 0    ) t1 on t1.jean_id = j2.id  sql 

jacket_types varies user input.

i tried following doesn't work , produces incorrect sql.

jacket_colors ||= [2,21,25,20]  jean.joins(:jacket_types, :track) .select('jeans.jacket_types_id jacket_types_id, count(jeans.id) no_count'). where('jeans.status in (?) , tracks.status = ? , tracks.type != ?', jacket_colors, 0, 'trekkingtrack') .group('jeans.jacket_types_id') .having('count(jeans.id) > ?', 0) .select('jacket_types.*, tracks.no_count').explain 

please try it, think work.

rails query version:

jacket_colors ||= [2,21,25,20]  jean.joins(:jacket_types => :track)  .where('jeans.status in (?) , tracks.status = ? , 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") 

of

jacket_colors ||= [2,21,25,20] jacket_types = jackettype.find_by_sql(<<-sql)   select j2.*, t1.no_count   jeans j2     inner join (       select       j1.jean_id jean_id,       count(j1.id) no_count       tracks t         inner join jacket_types j1 on j1.track_id = t.id         inner join jeans j2 on j2.id = j1.jean_id         t.status = 0         , j1.status in (#{jacket_colors})         , t.type != 'trekkingtrack'         group j1.jean_id         having count(j1.id) > 0    ) t1 on t1.jean_id = j2.id  sql 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -