I want to count the total no of Products
for a particular shopping list and then display the total count of products
for that shopping list according to its id in the Shopping List table
.I have created a reference for shopping_list in the product table
My Shopping list table is as follows:-
id serial NOT NULL,
shopping_list_name character varying(255),
shopping_list_status character varying(255) DEFAULT 'OPEN'::character varying,
total_items character varying(255) DEFAULT 0,
created_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL,
deleted integer NOT NULL DEFAULT 0,
CONSTRAINT shopping_lists_pkey PRIMARY KEY (id)
My Product table is as follows:-
id serial NOT NULL,
shopping_list_id integer NOT NULL,
product_name character varying(255) DEFAULT 'null'::character varying,
product_category character varying(255),
quantity integer,
status character varying(255) DEFAULT 'OPEN'::character varying,
deleted integer NOT NULL DEFAULT 0,
CONSTRAINT products_pkey PRIMARY KEY (id)
Can anyone Please Help me:-
So you will have something like
class ShoppingList < ActiveRecord::Base
has_many :products
end
class Product < ActiveRecord::Base
belongs_to :shopping_list
end
Then in order to get the number of products for a shopping list
@my_shopping_list.products.count
And to get the quantity
@my_shopping_list.products.sum(:quantity)
You can have some kind of cache on your shopping list, so lets say that you have an integer field named products_quantity on your ShoppingList, which by default is 0 (make sure to make it 0 by default, not nil).
Then on your Product model, you can do something like
class Product < ActiveRecord::Base
after_create :update_shopping_list
def update_shopping_list
shopping_list.update_attribute(:products_quantity, shopping_list.products_quantity + self.quantity)
end
end
In that case you don't have to execute the query SELECT SUM(quantity) FROM PRODUCTS WHERE shopping_list_id = ?
I'm not sure if I answer your second question, but if you have more questions or if you were trying to ask something else, just let me know.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.