Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 736
ciaoben Avatar asked Nov 26 '15 09:11

ciaoben


1 Answers

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'})
like image 80
user3506853 Avatar answered Sep 17 '22 23:09

user3506853