簡體   English   中英

Rails has_many 通過 has_and_belongs_to_many

[英]Rails has_many through has_and_belongs_to_many

我正在嘗試找到通過輔助 model 從 has_and_belongs_to_many 關聯獲取數據的方法。我現在要說對不起,因為我可能無法正確解釋這一點,所以最好只展示關聯以及我需要做什么。 我正在使用 Rails 5。

我有:

事件 Model:

incident has_and_belongs_to_many:apps

應用 Model:

app has_and_belongs_to_many:incidents

app belongs_to:service

客服Model:

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

您可以使用uniq_by

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

然后你可以做

@my_service.incidents.uniq_by(&:incident_id)

incidents添加到您的Service

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

然后

@service.incidents.uniq

@service.incidents.distinct

這個應該可以。

class Service
  has_many :apps
  has_many :incidents,  -> { distinct }, through: :apps
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM