Add counter for number of each product in order
This commit is contained in:
parent
64113790cf
commit
3553901b7c
4 changed files with 17 additions and 2 deletions
|
@ -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') }
|
||||
|
||||
|
|
|
@ -1,2 +1,3 @@
|
|||
class Product < ActiveRecord::Base
|
||||
has_one :order_product
|
||||
end
|
||||
|
|
|
@ -0,0 +1,5 @@
|
|||
class AddProductsCountToOrderProducts < ActiveRecord::Migration
|
||||
def change
|
||||
add_column :order_products, :count, :integer, default: 1
|
||||
end
|
||||
end
|
|
@ -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|
|
||||
|
|
Loading…
Reference in a new issue