On Tue, Feb 21, 2012 at 8:15 AM, LED <[email protected]> wrote:

> hi guys im playing with RoR with the environment of rails 3 ruby 1.9 i
> got stuck in
>
> nil can't be coerced into BigDecimal
>
> error
>
> i need to get the total cost of the products inside the cart i know
> where the problem is(i think) but i almost did every thing
> cart/show.html.rb
>
> <div class="cart_title" >Your Cart</div>
>    <table>
>        <% for item in @cart.line_items %>
>    <tr>
>        <td><%= item.quantity %>&times;</td>
>        <td><%= item.product.title %></td>
>    <td class="item_price" ><%= number_to_currency(item.total_price)
> %></td>
>    </tr>
>    <% end %>
>        <tr class="total_line" >
>        <td colspan="2" >Total</td>
>        <td class="total_cell" ><%=
> number_to_currency(@cart.total_price) %></td>
>    </tr>
>    </table>
>        <%= button_to 'Empty cart', @cart, :method => :delete,
>        :confirm => 'Are you sure?' %>
>
> model/line_item.rb
>
>  def total_price
>    line_items.to_a.sum { |item| item.total_price }
>  end
> model/cart.rb
>
>  def total_price
>    product.price  * quantity
>  end
> my second option is
>
> def total_price
>     if product.price
>       product.price * quantity
>     else
>       product.price = "0.0".to_d
>

This code is assigning a 0 to fixed price of a product
(most probably not what is intended). Probably simply
return a 0 (in BigDecimal) here.


>     end
>   end
> but still this wont work
>

Is there a business rule that each item must realistically have
a quantity and product (and that product must have a price) ?

In that case I suggest:

* add validations for the presence of these values
  (presence of quantity and product on item
   presence of price on product)

* write code like:

def total_price
    if self.valid?
      product.price * quantity
    else
      0.to_d
    end
  end


Another possible gotcha is that "item.product_id" is available
(e.g. from a select box), but item.product is not yet associated
(you may need to override the product_id= setter for that  e.g.

def product_id=(product_id)
  self.product = Product.find_by_id(product_id)
  super
end

HTH,

Peter


-- 
*** Available for a new project ***

Peter Vandenabeele
http://twitter.com/peter_v
http://rails.vandenabeele.com
http://coderwall.com/peter_v

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to