Taras Shpachenko Taras Shpachenko - 6 months ago 13
SQL Question

ActiveRocord query with polymorphic associations

I'm trying to get some records from table, but i don't know how to build this query.

I have some models.

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


So, I need to get all Notifications where source = some_request or source.request = some_request

Answer

Isn't it something simple as -

some_request.notifications
# or
some_decision.notifications

and if source is combination of request & decision then

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

Notification.find(notifications_ids)
Comments