Have in a module in ./lib:
module Pricing
def sell_price
(cost.to_f)/((100-(margn.to_f))/100)
end
def sell_price_inc
((product.cost.to_f)/((100-(product.margn.to_f))/100)*1.14)
end
def charge_excl
(sell_price).to_f * quantity
end
end
A model product:
class Product < ActiveRecord::Base
include Pricing
attr_accessible :name, :code, :cost, :company_id, :margn
belongs_to :company
has_many :allocations
has_many :companies, :through => :allocations
end
An allocation model:
class Allocation < ActiveRecord::Base
include Pricing
attr_accessible :company_id, :allocated_product_id, :quantity,
:saledate, :cost
belongs_to :company
belongs_to :allocated_product, :class_name => ‘Product’ #So you have
company.products and company.allocated_products.
end
A products and allocations controller:
class ProductsController < ApplicationController
def index
@products = Product.all
end
class AllocationsController < ApplicationController
def index
@products =Product.all
@allocations = Allocation.all
end
And the views in product index:
<td><%=h (sprintf( "R%.02f" ,product.sell_price)) %></td>
<td><%=h (sprintf( "R%.02f" ,product.sell_price_inc)) %></td>
The above works well !
However in my allocations model and view I am trying to show the price
based on quantity:
def charge_excl
(sell_price).to_f * quantity
end
I get the error: undefined local variable or method `cost’
It is obviously failing as it cannot get access to the cost parameter
and its not accessible
So in a nutshell I can run calculations on one model (product) in the
module but as soon as I require a calculation using two models data
(cost, margin and quantity) it fails
Help is appreciated thanks