I have a Product object that has many InventoryCurrent objects. Once a month all inventory transactions will be summed and a new InventoryCurrent record will be created for each product in each warehouse. This is done so that the system does not have to do hundreds of calculations every time current inventory is requested. I have created a from_warehouse scope as follows:
scope :from_warehouse, lambda {|warehouse| where(:warehouse_id =>warehouse) }
I would like 开发者_运维技巧to make a call to get the current inventory as follows:
product.current_inventories.from_warehouse(2).recent
This should return either the most current InventoryCurrent, or if one hasn't been created yet (because the product was just added) then it should return a new InventoryCurrent object with the proper warehouse_id and product_id set.
The problem is that scope returns a recordset, not a single object. I can't put this scope in a method and call .first because that might generate an error if the recordset is empty.
Any suggestions?
use find_or_create_by_warehouse_id_and_product_id
, or find_or_initialize_by_warehouse_id_and_product_id
. see this for more information.
精彩评论