ruby-on-rails-3activerecordpolymorphismpolymorphic-associations

Find all records of a certain type in Polymorphic table using ActiveRecord in Rails 3


I have a table Category that is a polymorphic model for a bunch of other models. For instance

model Address has shipping, billing, home, work category

model Phone has home, mobile, work, fax category

model Product has medical, it equipment, automotive, aerospace, etc categories.

What I want to be able to do is something like

Product.all_categories and get and array of all categories that are specific to this model.

Of course I can do something like this for each model in question:

Category.select("name").where("categorizable_type = ?","address")

Also pace_car - which is rails 3 ready, allows me to do something like this:

Category.for_category_type(Address)

But I was wondering if there is a more straightforward / elegant solution to this problem using Active Record iteself - without relying on a gem?


Solution

  • I'm not aware of anything built-in to ActiveRecord to give you this, but you could set up that for_category_type method in one line of code in your Category controller:

    scope :for_category_type, lambda { |class_name| where("categorizable_type = ?", class_name) }