Skip to content

Instantly share code, notes, and snippets.

@tmaximini
Created September 12, 2011 13:21
Show Gist options
  • Save tmaximini/1211231 to your computer and use it in GitHub Desktop.
Save tmaximini/1211231 to your computer and use it in GitHub Desktop.
get all products from category tree
# category.rb
class Category < ActiveRecord::Base
acts_as_nested_set
attr_accessible :name, :description, :lft, :rgt, :parent_id
has_many :categorizations
has_many :products, :through => :categorizations
attr_accessor :product_list
def branch_ids
self_and_descendants.map(&:id).uniq
end
def all_products
Category.find(branch_ids).map(&:products)
end
end
#categorization.rb
class Categorization < ActiveRecord::Base
belongs_to :product
belongs_to :category
end
# products_controller.rb
class ProductsController < ApplicationController
before_filter :authenticate_user!, :except => [:index, :show]
def index
if params[:category]
@category = Category.find(params[:category])
@products = @category.all_products # <-- get all products
else
@category = false
@products = Product.scoped
end
@products = @products.where("title like ?", "%" + params[:title] + "%") if params[:title]
@products = @products.order("created_at").page(params[:page]).per( params[:per_page] ? params[:per_page] : 12)
@categories = Category.all
end
#...
end
# console output
ruby-1.9.2-p136 :020 > c = Category.first
=> #<Category id: 6, name: "Woman", description: "woman stuff", created_at: "2011-08-24 13:10:11", updated_at: "2011-08-24 13:10:11", parent_id: nil, lft: 1, rgt: 6>
ruby-1.9.2-p136 :021 > Category.find(c.branch_ids).map(&:products)
=> [[#<Product id: 12, description: "test", price: 398000, created_at: "2011-07-11 10:48:13", updated_at: "2011-07-11 10:48:13", title: "Jewels", subtitle: "diamant", currency: "GBP", legacy: nil>], [], [#<Product id: 12, description: "test", price: 398000, created_at: "2011-07-11 10:48:13", updated_at: "2011-07-11 10:48:13", title: "Jewels", subtitle: "diamant", currency: "GBP", legacy: nil>]]
ruby-1.9.2-p136 :022 >
# output needed to be able to order and paginate products (example with only one category)
uby-1.9.2-p136 :022 > c = Category.first
=> #<Category id: 6, name: "Woman", description: "woman stuff", created_at: "2011-08-24 13:10:11", updated_at: "2011-08-24 13:10:11", parent_id: nil, lft: 1, rgt: 6>
ruby-1.9.2-p136 :023 > c.products
=> [#<Product id: 12, description: "test", price: 398000, created_at: "2011-07-11 10:48:13", updated_at: "2011-07-11 10:48:13", title: "Jewels", subtitle: "diamant", currency: "GBP", legacy: nil>]
ruby-1.9.2-p136 :024 >
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment