How to properly use joins on polymorphic association in Active Record
Asked Answered
B

1

6

I have a Model Action that has a

belongs_to :actor, polymorphic: true

that actor can be: a Customer, Admin, Seller or Guest.

I want to filter instances of Action to just the actions made by a particular Seller or Guest. How can I do that?

In a normal association, I would join the two tables, but this way, I don't know how properly do it.

Brittnee answered 26/11, 2015 at 9:3 Comment(0)
S
9

Hope this may helpful to you:-

class Action < ActiveRecord::Base
    belongs_to :actor, polymorphic: true

    scope :by_type, lambda { |type| joins("JOIN #{type.table_name} ON #{type.table_name}.id = #{Opinion.table_name}.opinionable_id AND #{Opinion.table_name}.opinionable_type = '#{type.to_s}'") }
end

Then call it like:-

Action.by_type(Seller).to_sql
=> "SELECT \"actions\".* FROM \"astions\" JOIN sellers ON sellers.id = actions.actorable_id AND actions.actorable_type = 'Seller'" 

Or you can achieve by this:-

belongs_to :actor, :foreign_key => :actorable_id, polymorphic: true

Action.joins(:actor).where('actors.actorable_id = ? AND actors.actorable_type = ?', seller_id, 'Seller'})
Sacroiliac answered 26/11, 2015 at 9:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.