-
Notifications
You must be signed in to change notification settings - Fork 28
Query methods
kostyantyn edited this page Sep 5, 2012
·
1 revision
Product.hydra_attributes.create(name: 'title', backend_type: 'string')
Product.hydra_attributes.create(name: 'price', backend_type: 'float')
Product.hydra_attributes.create(name: 'active', backend_type: 'boolean')
Product.hydra_attributes.create(name: 'total', backend_type: 'integer')
Product.create(title: 'toy1', price: 2.55, active: true, total: 5)
Product.create(title: 'toy2', price: 3.95, active: true, total: 2)
Product.create(title: 'toy3', price: 5.55, active: false, total: 4)
Product.create(title: 'toy5', price: 6.75, active: false, total: 2)
Product.where(active: true)
# [
#<Product id: 1, hydra_set_id: nil, created_at: ..., updated_at: ..., active: true, price: 2.55, title: "toy1", total: 5>,
#<Product id: 2, hydra_set_id: nil, created_at: ..., updated_at: ..., active: true, price: 3.95, title: "toy2", total: 2>
# ]
Product.select(:title)
# [
#<Product id: 1, hydra_set_id: nil, title: "toy1">,
#<Product id: 2, hydra_set_id: nil, title: "toy2">,
#<Product id: 3, hydra_set_id: nil, title: "toy3">,
#<Product id: 4, hydra_set_id: nil, title: "toy5">
# ]
Product.order(:total)
# [
#<Product id: 2, hydra_set_id: nil, created_at: ..., updated_at: ..., active: true, price: 3.95, title: "toy2", total: 2>,
#<Product id: 4, hydra_set_id: nil, created_at: ..., updated_at: ..., active: false, price: 6.75, title: "toy5", total: 2>,
#<Product id: 3, hydra_set_id: nil, created_at: ..., updated_at: ..., active: false, price: 5.55, title: "toy3", total: 4>,
#<Product id: 1, hydra_set_id: nil, created_at: ..., updated_at: ..., active: true, price: 2.55, title: "toy1", total: 5>
# ]
Product.order(:total).reverse_order
# [
#<Product id: 1, hydra_set_id: nil, created_at: ..., updated_at: ..., active: true, price: 2.55, title: "toy1", total: 5>,
#<Product id: 3, hydra_set_id: nil, created_at: ..., updated_at: ..., active: false, price: 5.55, title: "toy3", total: 4>,
#<Product id: 2, hydra_set_id: nil, created_at: ..., updated_at: ..., active: true, price: 3.95, title: "toy2", total: 2>,
#<Product id: 4, hydra_set_id: nil, created_at: ..., updated_at: ..., active: false, price: 6.75, title: "toy5", total: 2>
# ]
Product.group(:total).count
# {2=>2, 4=>1, 5=>1}