Polymorphic associations’ as and where is used in SQL


You are using a polymorphic association in your application, and you would like to know how exactly the as declaration in your model has_many is used in the SQL by ActiveRecord. So following the example in the Rails Guides with the following models:


class Picture < ActiveRecord::Base
  belongs_to :imageable, :polymorphic => true

class Employee < ActiveRecord::Base
  has_many :pictures, :as => :imageable

class Product < ActiveRecord::Base
  has_many :pictures, :as => :imageable


ActiveRecord uses the as in the model declaration as a guide to find the foreign id key in the polymorphic association, by adding the _id to the :as name. So following the
example above the query for the product would be:

SELECT `images`.*
FROM `images`
WHERE (`ratings`.imageable_id = 289
      AND `images`.imageable_type = 'Product')