Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails joins or preload belongs_to association from polymorphic model

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!

like image 917
Schovi Avatar asked Apr 28 '11 07:04

Schovi


People also ask

How is polymorphic association set up in Rails?

The basic structure of a polymorphic association (PA)sets up 2 columns in the comment table. (This is different from a typical one-to-many association, where we'd only need one column that references the id's of the model it belongs to). For a PA, the first column we need to create is for the selected model.

What is polymorphic association rails?

In Ruby on Rails, a polymorphic association is an Active Record association that can connect a model to multiple other models. For example, we can use a single association to connect the Review model with the Event and Restaurant models, allowing us to connect a review with either an event or a restaurant.


1 Answers

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})
like image 79
zacksiri Avatar answered Oct 29 '22 01:10

zacksiri