重写范围以使用ActiveRecord帮助程序

时间:2017-06-20 06:05:34

标签: ruby-on-rails ruby activerecord

我的模型中有以下范围:

  scope :by_attributes, ->(names) {
    attribute_ids = ReferralPartnerAttribute.where(name: names).pluck(:id)
    if attribute_ids.any?
      where(
        "ARRAY[?] <@ (
          SELECT array_agg(referral_partner_attribute_id)
          FROM referral_partner_referral_partner_attributes
          WHERE referral_partner_referral_partner_attributes.referral_partner_id = referral_partners.id)", attribute_ids
      )
    else
      none
    end
  }

如何以更多ActiveRecor方式重写它?这可能吗?

1 个答案:

答案 0 :(得分:1)

如何在范围内调用另一个范围?

scope :by_attributes, ->(names) { (attribute_ids = ReferralPartnerAttribute.where(name: names).pluck(:id)).present? ? another_scope(attribute_ids) : none }
scope :another_scope, ->(attribute_ids) { where("ARRAY[?] <@ (
        SELECT array_agg(referral_partner_attribute_id)
        FROM referral_partner_referral_partner_attributes
        WHERE referral_partner_referral_partner_attributes.referral_partner_id = referral_partners.id)", attribute_ids
      )}

如果您已经拥有attribute_ids并且不需要检查它是否为空,这样做也有助于直接调用此范围。