I guess I am not being clear on what I am looking for
What I want is for a product X (example: 24710089) to show the
current_stock in all locations. Show I should get some array/hash that
allows me to output
Product 24710089
Location A: 10
Location C: 20
etc.
Ahh… I thought you wanted to be able to have stock at each location, and then have the total stock (which is what product.current_stock does right now). I’m going to go ahead and leave that alone, and show you another function that will do what you want (that way you can do either one)
class Product < ActiveRecord::Base
has_many :mutations
has_many :locations, :through => :mutations
def current_stock
Mutation.find_all_by_product_id(self.id).inject(0) {|total, mut|
total += mut.mutation}
end
end
def location_stocks
Mutation.find_all_by_product_id(self.id).each {|m| location_stock[m.location_id] = m.mutation}
location_stock
end
Now let’s say you have two locations, location1 and location2.
location1’s id = 14839, current stock = 24
location2’s id = 19248, current stock = 94
If each of those locations had product 24710089 in it, and you did
l = Product.find(24710089).location_stocks
then
l[14839] == 24
l[19248] == 94
Or, in Ruby parlance
l == {14839 => 24, 19248 => 94}
Will that do what you want?
class Mutation < ActiveRecord::Base
belongs_to :product
belongs_to :location
def mutation
mutation = 0 + self.buy - self.sell - self.transit - self.lost
end
end
class Location < ActiveRecord::Base
has_many :mutations
has_many :products, :through => :mutations
You probably don’t want current_stock here, unless you want it to show the stock of all the products at this location
If you do, it’s:
def current_stock
Mutation.find_all_by_location_id(self.id).each {|m| product_stock[m.product_id] = m.mutation}
product_stock
end
This will be
product_stock == {24710089 => 24} for location1
and
product_stock == {24710089 => 94} for location2