Guest User

Untitled

a guest
Apr 20th, 2018
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. class CreateOrders < ActiveRecord::Migration[5.1]
  2. def change
  3. create_table :orders do |t|
  4. t.timestamps
  5. end
  6. end
  7. end
  8.  
  9. class CreateOrderItems < ActiveRecord::Migration[5.1]
  10. def change
  11. create_table :order_items do |t|
  12. t.integer :order_id, index:true
  13. t.integer :product_id, index:true
  14. t.integer :amount
  15. t.timestamps
  16. end
  17. end
  18. end
  19.  
  20. class CreateProducts < ActiveRecord::Migration[5.1]
  21. def change
  22. create_table :products do |t|
  23. t.text :name
  24. t.integer :family_id, index:true
  25. t.timestamps
  26. end
  27. end
  28. end
  29.  
  30. class CreateFamilies < ActiveRecord::Migration[5.1]
  31. def change
  32. create_table :families do |t|
  33. t.text :name
  34. t.timestamps
  35. end
  36. end
  37. end
  38.  
  39. class Family < ApplicationRecord
  40. has_many :products
  41. end
  42.  
  43. class Order < ApplicationRecord
  44. has_many :order_items
  45. has_many :products, through: :order_items
  46. end
  47.  
  48. class OrderItem < ApplicationRecord
  49. belongs_to :order
  50. belongs_to :product
  51. end
  52.  
  53. class Product < ApplicationRecord
  54. belongs_to :family
  55. has_many :order_items
  56. end
  57.  
  58. irb(main):015:0> Order.joins(:order_items).joins(:products).where("products.family_id":2).where("orders.created_at": [(Time.now).to_date..(Time.now + 1.day).to_date]).count
  59. (0.6ms) SELECT COUNT(*) FROM "orders" INNER JOIN "order_items" ON "order_items"."order_id" = "orders"."id" INNER JOIN "order_items" "order_items_orders_join" ON "order_items_orders_join"."order_id" = "orders"."id" INNER JOIN "products" ON "products"."id" = "order_items_orders_join"."product_id" WHERE "products"."family_id" = ? AND ("orders"."created_at" BETWEEN '2018-04-20' AND '2018-04-21') [["family_id", 2]]
  60. => 3
Add Comment
Please, Sign In to add comment