【问题标题】:Nested AREL and/or query in RailsRails 中的嵌套 AREL 和/或查询
【发布时间】:2020-04-30 12:04:23
【问题描述】:

我相信这对于知道自己在做什么的人来说会很简单。我想将此语句写为一个范围 - 我宁愿使用 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。我显然会发送我需要的身份证件

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

【问题讨论】:

  • 你的 Rails 版本是什么?

标签: ruby-on-rails ruby arel


【解决方案1】:

也许你想要这样的东西:

class Contact < ApplicationRecord
   scope :contact_type_eq, lambda { |contact_type| 
     where(contact_type: contact_type) 
   }

   scope :shaitan_eq, lambda { |shaitan|
     where(
       shaitan_type: shaitan.class.to_s, 
       shaitan_id: shaitan.id
     )
   }

   scope :shaitan_colect_with_type, lambda { |shaitans, types|
     main_scope = contact_type_eq(types)
     scope = main_scope.shaitan_eq(shaitans.first)
     shaitans[1..-1].each do |shaitan|
       scope = scope.or(main_scope.shaitan_eq(shaitan))
     end
     scope
   }
end

您可以将其用作:

Contact.shaitan_colect_with_type([developer, development], [1,2])

Contact.contact_type_eq([1,2])
       .shaitan_eq(developer)
       .or(
          Contact.contact_type_eq([1,2])
                 .shaitan_eq(development)
        )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-23
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-24
    相关资源
    最近更新 更多