Agile Web Development Book, need a bit of help

collection.each do |object|    object.stuff end

is equivalent to

for object in collection    object.stuff end

Just try having collection be something that doesn't respond_to "each" and see the error that the 'for' version gives you.

(I know that I'm not really answering the OP's question about the cart or the BigDecimal error, but the suggestion in the first response isn't valid or even syntactically correct.)


Rob Biedenharn

In a view perhaps?

<% if @items -%>    <ul>      <% @items.each do |item| -%>        <li><%= item %></li>      <% end -%>    </ul> <% else -%>    <p>Sorry, no items</p> <% end -%>

You could say 'unless @items.blank?' in place of 'if @items' with the same result.


Rob Biedenharn

I found if I changed the code to this:

<h1>Display Cart</h1> <table>

<thead> <tr><th>Title</th></tr> </thead> <tbody>

<% for item in @items %>

<% for item in @cart.items %>

<%= item%>

<tr><td><%= item.title %></td></tr>

<% end %>



It printed out just the price field from the database, which makes me think perhaps something is wrong with my model?

Here's my table: id title description image_url price date_available

Here's my model:

class Cart   attr_reader :items   attr_reader :total_price

  def initialize   @items =   @total_price = 0.0   end

  def add_product(product)     @items << LineItem.for_product(product)     @total_price += product.price   end end

Thanks for the help.

Mark --

Without seeing what you're doing in the controller, that's all I can say.


Rob Biedenharn

So does the view work now? You can also have: <%= item.inspect %>

to find out what item is (if it's nil, nil.inspect => "nil")


Rob Biedenharn

Good point. Using debug() also puts some nice CSS classes on the output so you can format it (like display:none;) and still get to it in the "view source" or by changing the CSS dynamically (Firebug or alternate stylesheets)


Rob Biedenharn

That's the class into which database floats and decimal values are reified. It is a class that retains decimal places accurately (something that is simply not possible with binary-encoded approximations to real decimal numbers).


Rob Biedenharn