Actually I’m trying to perform a multiplication on a project.I have 2 models : a parent model and a child model.I want to show the result of the multiplication performed on the child model in the parent view by invoking the multiplication method.Here’s the code:
app/models/drink.rb aka child model
class Drink < ActiveRecord::Base
belongs_to :menu
before_create :total_amount
before_save :total_amount
def total_amount
self.quantity * self.price * 1.30
end
end
> in app/models/menu.rb aka parent model
class Menu < ActiveRecord::Base
has_many :drinks, :dependent => :destroy
accepts_nested_attributes_for :drinks, :allow_destroy => true
end
in views/menu/show.html.erb
<td><%=number_to_currency(@menu.total_amount) %> </td>
and the error message:
undefined method `total_amount’ for nil:NilClass
Obviously total_amount is an attribute of the model drink .What am I doing wrong.Thanks for helping.
Matter fact the problem is that the quantity and the price of the drink was not set.A part of the solution comes from Wizard of Ogz.Matter fact by trying to solve a “nil can’t be coerced into BigDecimal” I get the solution to this issue too.So here’s is the solution
1-app/models/drink.rb aka child model
Apply to self.quantity and self.price a method which convert them to string(to_s) then to big decimal(to_d)
2-app/models/drink.rb aka child model
validates the presence of price and quantity before saving them to the database
3-app/views/menus/show.html.erb aka parent model
Simply apply the method total_amount to dink aka child(nested) model as following:
Thanks to Wizard of Ogz, Mitch Dempsey, sosborn, and Misha M