Add counter for number of each product in order

This commit is contained in:
Benjamin Cousaert 2014-11-29 11:06:22 +01:00
parent 64113790cf
commit 3553901b7c
4 changed files with 17 additions and 2 deletions

View file

@ -1,7 +1,15 @@
class Order < ActiveRecord::Base
belongs_to :user
has_many :order_products
has_many :products, through: :order_products
has_many :products, -> { includes :order_product }, { through: :order_products} do
def << (product)
if proxy_association.owner.products.include?(product)
proxy_association.owner.order_products.find_by(product: product).increment!(:count, 1)
else
super
end
end
end
default_scope -> { order('created_at DESC') }

View file

@ -1,2 +1,3 @@
class Product < ActiveRecord::Base
has_one :order_product
end

View file

@ -0,0 +1,5 @@
class AddProductsCountToOrderProducts < ActiveRecord::Migration
def change
add_column :order_products, :count, :integer, default: 1
end
end

View file

@ -11,11 +11,12 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20141125130447) do
ActiveRecord::Schema.define(version: 20141128123152) do
create_table "order_products", force: true do |t|
t.integer "order_id"
t.integer "product_id"
t.integer "count", default: 1
end
create_table "orders", force: true do |t|