【发布时间】:2018-02-09 13:44:59
【问题描述】:
我正在尝试寻找通过辅助模型从 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
【问题讨论】:
标签: ruby-on-rails ruby has-and-belongs-to-many has-many-polymorphs