has_ranking support for HABTM associations #34

Closed
ghost opened this Issue Oct 27, 2012 · 0 comments

Projects

None yet

1 participant

@ghost
ghost commented Oct 27, 2012

Hi I was wondering if there is any plan to support has_ranking for HABTM associations.

With this I mean:

Let's suppose I have two models:

class Category < ActiveRecord::Base
include Pacecar

attr_accessible :description, :name
validates :description, presence: true
validates :name, presence: true
validates :name, uniqueness: true

has_and_belongs_to_many :products
has_ranking :products
end

class Product < ActiveRecord::Base
include Pacecar

attr_accessible :description, :name, :price
validates :description, presence: true
validates :name, presence: true
validates :name, uniqueness: true
validates :price, numericality: true
validates :price, presence: true

has_and_belongs_to_many :categories
end

And I have a standard join table categories_products with a foreign key category_id and product_id

The standard has_ranking for has_many associations actually invokes the current query:

SELECT "categories".*, count("products"."category_id") as products_count FROM "products" inner join "products on "products"."category_id" = "categories."id" GROUP BY "categories"."id", "categories"."name", "categories"."description", "categories"."created_at", "categories"."update
d_at" ORDER BY products_count desc

The idea in a HABTM query is to inner join the categories table with the categories_products and count the product_id instead, so the query would end up being like:

SELECT "categories".*, count("categories_products"."product_id") as products_count FROM "products" inner join "categories_products on "categories_products"."category_id" = "categories."id" GROUP BY "categories"."id", "categories"."name", "categories"."description", "categories"."created_at", "categories"."update
d_at" ORDER BY products_count desc

I haven't dug up very much in the ActiveRecord API to see if there is a way to access the "join table" of a relation on the fly and if there's any way to differentiate between a has_many and a has_and_belongs_to_many associations from a symbol representing the association's name

If such thing is possible you can haven a if statement in the Raking module and setup one query or another depending on the association type

@mjankowski mjankowski closed this Oct 28, 2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment