Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It looks like you have not specified <code>opinionable_type:string</code> column for your Opinion model.</p> <p>Try to update your migration in this manner:</p> <pre><code>class CreateOpinions &lt; ActiveRecord::Migration def self.up create_table :opinions do |t| t.integer :opinionable_id t.string :opinionable_type # ... other fields t.timestamps end end def self.down drop_table :opinions end end </code></pre> <p>This will solve your second question and <code>Opinion.preload(:opinionable).all</code> should work well.</p> <p>You cann't do joins on polymorphic association because they can be located in different tables, which are detected after <code>Opinion</code> model is loaded. That why model needs column <code>opinionable_type</code>.</p> <p>If you try to do this you'll get next exception</p> <blockquote> <p><code>ActiveRecord::EagerLoadPolymorphicError</code>: Can not eagerly load the polymorphic association <code>:opinionable</code></p> </blockquote> <p>UPD: Added magic join ^_^</p> <pre><code>class Opinion &lt; ActiveRecord::Base belongs_to :opinionable, :polymorphic =&gt; true belongs_to :opinionable_answer, :foreign_key =&gt; :opinionable_id, :class_name =&gt; "Answer" 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 </code></pre> <p>Example:</p> <pre><code>Opinion.by_type(Answer).to_sql =&gt; "SELECT \"opinions\".* FROM \"opinions\" JOIN answers ON answers.id = opinions.opinionable_id AND opinions.opinionable_type = 'Answer'" </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload