0

我试图找到通过辅助模型从 has_and_belongs_to_many 关联中获取数据的方法。我现在要说抱歉,因为我可能无法正确解释这一点,所以最好我只是展示关联和我需要做的事情。我正在使用 Rails 5。

我有:

事件模型:

incident has_and_belongs_to_many :apps

应用模型:

app has_and_belongs_to_many :incidents

app belongs_to :service

服务模式:

has_many :apps

我想为我的给定服务找到它通过其拥有的应用程序参与的事件,但我只想要唯一的事件。

有什么方法可以让我@service.apps_incidents.unique获得独特事件的列表。

我的迁移看起来像这样:

服务表:

class CreateServices < ActiveRecord::Migration[5.1]
  def change
    create_table :services do |t|
      t.string :name
      t.timestamps
    end
  end
end

应用表:

class CreateApps < ActiveRecord::Migration[5.1]
  def change
    create_table :apps do |t|
      t.string :name
      t.references :service, foreign_key: true
      t.timestamps
    end
  end
end

事故表:

class CreateIncidents < ActiveRecord::Migration[5.1]
  def change
    create_table :incidents do |t|
      t.string :name
      t.timestamps
    end
  end
end

应用程序/事件加入表:

class CreateJoinTableAppsIncidents < ActiveRecord::Migration[5.1]
  def change
    create_join_table :apps, :incidents do |t|
      t.index [:incident_id, :app_id]
    end
  end
end
4

2 回答 2

0

添加incidents到您的Service

class Service
  has_many :apps
  has_many :incidents, through: :apps
end

然后

@service.incidents.uniq

或者

@service.incidents.distinct

这应该做。

于 2020-03-04T15:53:32.140 回答
0

您可以使用uniq_by

class Service
  has_many :apps
  has_many :incidents, through: :apps
end

然后你可以做

@my_service.incidents.uniq_by(&:incident_id)
于 2018-02-09T13:59:02.230 回答