ActiveRecord加入自己的id数组

时间:2019-03-01 00:32:47

标签: ruby-on-rails activerecord

我想用第一个模型的联接和位置将查询链接起来

FbGroup.joins(:fb_posts).where(id: [1,2])
# this returns a lot of extra rows

FbGroup.joins(:fb_posts).where('fb_groups.id IN (?)', acct_ids)
# also tried this with no luck

在进行联接时,如何首先按具有特定ID的fb_groups进行过滤?

2 个答案:

答案 0 :(得分:0)

仅同时使用这两种方法是否奏效?

alter table t add email_id int;

update t join
       (select email, row_number() over (order by email) as rn
        from (select distinct email from t order by email) t 
       ) tt
       on t.email = tt.email
    set t.email_id = tt.rn;

您也可以使用的PS

FbGroups.joins(:fb_groups).where(id: [1,2]).where('fb_groups.id IN (?)', acct_ids)

或者,因为两个FbGroups.joins(:fb_groups).where(id: [1,2]).where(fb_groups: {id: acct_ids}) 现在都使用哈希参数:

where

答案 1 :(得分:0)

FbGroup.distinct.joins(:fb_posts).where
              .not(id: FbGroup.joins(:fb_posts)
                       .where(fb_groups: {id: [1,2]}).distinct)