Active Record - 转换SQL查询

时间:2017-05-04 20:36:08

标签: ruby-on-rails activerecord

我在将SQL查询转换为ActiveRecord时遇到问题,我希望您能提供帮助。

  select tbl2.id
       from Table1 tbl1
              JOIN Table2 tbl2 ON tbl1.id = tbl2.some_column_id
       where tbl1.id in (1, 2, 3, 4, 5)
              and tbl2.id not in (10, 13, 22, 44, 66) 

Rails模型存在且关系如下:

表2:

has_many :table1

1 个答案:

答案 0 :(得分:1)

假设您使用适当的表名设置类(table1和table2不是rails模型的好名称,顺便说一句)。

然后

Table2
  .select(:id).joins(:table1)
  .where(table1: { id: [1, 2, 3, 4, 5] }
  .where.not(id: [10, 13, 22, 44, 66])
相关问题