我试图找到通过辅助模型从 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