具有多态关联的ActiveRocord查询

时间:2016-06-02 10:09:17

标签: sql ruby-on-rails postgresql ruby-on-rails-4 activerecord

我正在尝试从表中获取一些记录,但我不知道如何构建此查询。

我有一些模特。

class Request < ActiveRecord::Base
  has_many :notifications, as: :source
  has_many :decisions, dependent: :destroy
end

class Notification < ActiveRecord::Base
  belongs_to :source, polymorphic: true
end

class Decision < ActiveRecord::Base
  has_many :notifications, as: :source
  belongs_to :request
end

所以,我需要获取所有通知,其中source = some_request或source.request = some_request

2 个答案:

答案 0 :(得分:0)

您的查询应为Notification.where(source_id: some_request.id, source_type: 'Request')

参考Active record association

答案 1 :(得分:0)

不是简单的 -

some_request.notifications
# or
some_decision.notifications

如果来源是请求和组合的组合那么决定

notifications_ids = some_request.notifications.pluck(:id) +
some_decision.notifications.pluck(:id)

Notification.find(notifications_ids)
相关问题