Rails joins or preload belongs_to association from polymorphic model

Schovi picture Schovi · Apr 28, 2011 · Viewed 14.6k times · Source

my problem is following. How can I joins belongs_to association from polymorphic model

There is situation

opinion.rb

class Opinion < ActiveRecord::Base
    belongs_to :opinionable, :polymorphic => true
    belongs_to :category
end

answer.rb

class Answer < ActiveRecord::Base
    has_many :opinions, :as => :opinionable
end

How can i do following

Opinion.joins(:opinionabe).all

it will throw

ArgumentError: You can't create a polymorphic belongs_to join without specifying the polymorphic class!

How can i specific which class i want to join?

Second question. How to preload it?

Opinion.preload(:opinionable).all

works fine. It will do query for each class in belongs_to.

But. if i want to do something like

Opinion.preload(:opinionable => :answer_form).all

there is problem because one model has this association and second hasn't. So it will throw exception.

So how i can do something like

Opinion.preload(:answer => :answer_form, :another_belongs_to_model).all

?

Thanks, David!

Answer

zacksiri picture zacksiri · Aug 8, 2012

Actually if you just do

belongs_to :opinionable_answer, :foreign_key => :opinionable_id, :class_name => "Answer", conditions: { opinions: { opinionable_type: "Answer"}}

then you can do

Opinion.joins(:opinionable_answer).where(answers: { awesome: true})