Skip to content

Instantly share code, notes, and snippets.

@danhunter
Created August 29, 2012 00:10
Show Gist options
  • Save danhunter/3505531 to your computer and use it in GitHub Desktop.
Save danhunter/3505531 to your computer and use it in GitHub Desktop.
class Category < ActiveRecord::Base
has_many :subcategories, :dependent => :destroy
has_many :users, :through => :subcategories
end
# This..
Category.first.users
# ..generates this:
SELECT "users".* FROM "users" INNER JOIN "categorizations" ON "users"."id" = "categorizations"."user_id" INNER JOIN "subcategories" ON "categorizations"."subcategory_id" = "subcategories"."id" WHERE "subcategories"."category_id" = 1
# Is there something like this..
Category.find([1, 2]).users
# That would generate this:
SELECT "users".* FROM "users" INNER JOIN "categorizations" ON "users"."id" = "categorizations"."user_id" INNER JOIN "subcategories" ON "categorizations"."subcategory_id" = "subcategories"."id" WHERE "subcategories"."category_id" IN (1, 2)
# ..besides this:
User.find_by_sql('SELECT "users".* FROM "users" INNER JOIN "categorizations" ON "users"."id" = "categorizations"."user_id" INNER JOIN "subcategories" ON "categorizations"."subcategory_id" = "subcategories"."id" WHERE "subcategories"."category_id" IN (1, 2)')
class Subcategory < ActiveRecord::Base
belongs_to :category
has_many :categorizations
has_many :users, :through => :categorizations
end
class User < ActiveRecord::Base
has_many :categorizations
has_many :subcategories, :through => :categorizations
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment