2017-05-04 105 views
-1

我無法將SQL查詢轉換爲ActiveRecord,我希望你能幫忙。活動記錄 - 轉換SQL查詢

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

以爲你設置適當的表名的類(表1和表2是不是軌機型好名字,順便說一句)。

然後

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