blawzoo
blawzoo

Reputation: 2485

Ruby on Rails calculation

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.

Upvotes: 0

Views: 1198

Answers (3)

blawzoo
blawzoo

Reputation: 2485

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)

class Drink < ActiveRecord::Base
  belongs_to :menu 
  before_save :total_amount 

  def total_amount
    self.quantity.to_s.to_d * self.price.to_s.to_d * 1.30
  end   
end

2-app/models/drink.rb aka child model validates the presence of price and quantity before saving them to the database

class Drink < ActiveRecord::Base
      belongs_to :menu 
      before_save :total_amount

      validates :price, :presence => true 
      validates :quantity, :presence => true 

      def total_amount
        self.quantity.to_s.to_d * self.price.to_s.to_d * 1.30
      end   
end

3-app/views/menus/show.html.erb aka parent model

Simply apply the method total_amount to dink aka child(nested) model as following:

<td><%=number_to_currency(drink.total_amount) %> </td>

Thanks to Wizard of Ogz, Mitch Dempsey, sosborn, and Misha M

Upvotes: 1

sosborn
sosborn

Reputation: 14694

Obviously total_amount is an attribute of the model drink .

Yeah, that method is in the drink model (by the way, if it is an attribute then it is declared in your migration. The way you have it set up the total_amount will not be saved in the database), but, you are calling it on an instance of Menu.

As Misha M said, @menu.drinks.total_amount.

Upvotes: 2

Mitch Dempsey
Mitch Dempsey

Reputation: 39869

You need to add a function called total_amount to your Menu class, and then have it iterate through all the drinks, and sum the total amount of each drink.

Upvotes: 1

Related Questions