ciaoben
ciaoben

Reputation: 3378

How to properly use joins on polymorphic association in Active Record

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.

Upvotes: 6

Views: 4102

Answers (1)

user3506853
user3506853

Reputation: 814

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'})

Upvotes: 9

Related Questions