Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 在Rails中获取具有条件的关联对象计数_Sql_Ruby On Rails_Associations - Fatal编程技术网

Sql 在Rails中获取具有条件的关联对象计数

Sql 在Rails中获取具有条件的关联对象计数,sql,ruby-on-rails,associations,Sql,Ruby On Rails,Associations,我有以下型号的商品、优惠和礼品卡。我想得到所有相关的优惠和礼品卡与某些条件 它们之间的联系: 商人.rb has_many :offers has_many :gift_cards 礼品卡.rb: belongs_to :merchant offer.rb: belongs_to :merchant 为了直接得到计数,我可以做 Merchant.pluck( :id, Arel.sql('COUNT(offers.id)'), Arel.sql('MAX(offers.id)'),

我有以下型号的商品、优惠和礼品卡。我想得到所有相关的优惠和礼品卡与某些条件

它们之间的联系:

商人.rb

has_many :offers
has_many :gift_cards
礼品卡.rb:

belongs_to :merchant
offer.rb:

belongs_to :merchant
为了直接得到计数,我可以做

Merchant.pluck(
    :id, Arel.sql('COUNT(offers.id)'), Arel.sql('MAX(offers.id)'),
     Arel.sql('COUNT(gift_cards.id)'), Arel.sql('MAX(gift_cards.id)')
 )
但问题是,我有一系列合格的赠品ID和合格的礼品卡ID。我想获得商户的合格优惠/合格礼品卡数量

我可以执行类似于以下代码的操作来获取计数

merchant.offer_ids & eligible_offer_ids
但是有没有一种方法可以修改查询以获得合格的_优惠,而不是商户中的所有优惠

类似于下面的查询

    Merchant.pluck(
    :id, Arel.sql('COUNT(eligible_offer_ids.id)'), Arel.sql('MAX(eligible_offer_ids.id)'),
     Arel.sql('COUNT(eligible_gift_card_ids.id)'), 
     Arel.sql('MAX(gift_eligible_gift_card_id.id)')
 )

这将返回商户ID、优惠数量和礼品卡数量的ActiveRecord关系,其中符合条件的优惠和礼品卡ID位于这些数组中。然后,您可以根据需要进行迭代:D

您可以粘贴模型/关系吗?
Merchant.joins(:offers, :gift_cards)
  .select('merchants.id, COUNT(gift_cards) as offer_count, 
           COUNT(gift_cards) as gift_card_count')
  .where(offers: { id: eligible_offer_ids }, 
         gift_cards: { id: eligible_gift_cards_ids })
  .group(:id)