I am creating an inventory system, in which I have the following 2 models:
Product Model
class CreateProducts < ActiveRecord::Migration[5.2]
def change
create_table :products do |t|
t.string :name
t.float :price
t.integer :weight
t.string :unity
t.timestamps
end
end
end
Inventory Transactions Model This registers the amount of items to enter or to leave the inventory for each product, for this I have added a Boolean field, which will determine the type of transaction, whether purchase or sale
class CreateInventoryTransactions < ActiveRecord::Migration[5.2]
def change
create_table :inventory_transactions do |t|
t.string :invoice
t.integer :product_id
t.integer :quantity
t.boolean :transaction_type
t.timestamps
end
end
end
In this case I made a purchase transaction of 100 items of the same product, but at the time of trying to print that data of that product in the loop, it generates an error, and obvious given that this product has many transactions of purchase or sale, how would you print the sum of purchase transactions, or sales within the loop, for each product?
<% @products.each do |product| %>
<tr>
<td>-</td>
<td><%= product.name %></td>
<td><%= product.price %></td>
<td><%= product.weight %></td>
<td><%= product.unity %></td>
<td><%= product.inventory_transactions.quantity %></td>
</tr>
<% end %>
Avoiding the error of: undefined method 'quantity' for #<InventoryTransaction::ActiveRecord_Associations_CollectionProxy:0x007fdc3d68c038>