首页 > 解决方案 > 我想通过以下方式获得`has_many的不同记录:`关联

问题描述

我有一个关联的数据库,如下所示:

class Subscription < ActiveRecord::Base
  belongs_to :plan
  has_one :role, through: :plan
end

class Plan < ActiveRecord::Base
  has_many :subscriptions
  belongs_to :role
end

class Role < ActiveRecord::Base
  has_one :plan
end

我想要所有有roles.name = 'Gold'但只有不同的订阅role_id

在我执行了这个查询之后:

Subscription.includes(:plan => [:role]).where("roles.name = 'Gold'")

我得到的结果如下:

|  subscription_id   |   plan_id     |   role_id    |
|         1          |      1        |      3       |
|         2          |      1        |      3       |
|         3          |      1        |      3       |
|         4          |      2        |      4       |
|         5          |      2        |      4       |
|         6          |      3        |      5       |

role_id我想要的结果是(由or区分plan_id,任何一个都可以工作,因为has_one它们之间存在关联)。我尝试运行以下查询,但它选择 distinct onsubscription.id从而给出相同的结果:

Subscription.includes(:plan => [:role]).where("roles.name = 'Gold'").distinct("role_id")

我想要的结果:

|  subscription_id   |   plan_id     |   role_id    |
|         1          |      1        |      3       |
|         4          |      2        |      4       |
|         6          |      3        |      5       |

有没有办法通过 activerecord 来实现这一点,还是我必须运行一个each循环才能role_id在收到的结果上获得不同的值?

标签: sqlruby-on-rails-4inner-joindistinctrails-activerecord

解决方案


推荐阅读