嵌套的AREL和/或Rails中的查询

问题描述 投票:0回答:1

我确信这对于知道自己在做什么的人来说很简单。我想将此语句写为作用域-我宁愿使用Arel格式,但无法计算AND内的OR

select * from contacts where contact_type in (1,2) and 
((contactable_type = 'Developer' and contactable_id = 10) or (contactable_type = 'Development' and contactable_id = 24))

因此,开始我的范围-第一步很简单

scope :of_type,
        lambda { |types|
            where(contact_type: types)
        }

但是它是我无法获得的带有嵌套OR的AND。我显然会发送我需要的ID

scope :of_type,
        lambda { |types, developer_id, development_id |
            where(contact_type: types) .. .
        }
ruby-on-rails ruby arel
1个回答
0
投票

这是Arel方法:

Contact.select(Arel.star).where(
  Contact.arel_table[:contact_type].in([1, 2]).and(
    Contact.arel_table[:contactable_type].eq('Developer').and(Contact.arel_table[:contactable_id].eq(10)).or(
      Contact.arel_table[:contactable_type].eq('Development').and(Contact.arel_table[:contactable_id].eq(24))
    )
  )
)

这是活动记录之一:

contacts = Contact.where(contact_type: [1, 2])
contacts.where(contactable_type: 'Developer', contactable_id: 10).or(contacts.where(contactable_type: 'Development', contactable_id: 24))

如果您能够使用后者,那么恕我直言更好。

© www.soinside.com 2019 - 2024. All rights reserved.