【问题标题】:Rails has_many through has_and_belongs_to_manyRails has_many 到 has_and_belongs_to_many
【发布时间】: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


    【解决方案1】:

    您可以使用uniq_by

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

    你可以这样做

    @my_service.incidents.uniq_by(&:incident_id)
    

    【讨论】:

    • 谢谢,我知道这必须很简单,在星期五想太多。我确实收到了上面的错误:NoMethodError (undefined method uniq_by' for #<:activerecord_associations_collectionproxy:0x0000559ad7a8a8a0>)` 但是当我运行时:@my_service.incidents.distinct.pluck(:incident_id) 我得到了正确的结果
    【解决方案2】:

    incidents 添加到您的Service

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

    然后

    @service.incidents.uniq
    

    @service.incidents.distinct
    

    应该这样做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-13
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多