Wednesday, October 18, 2006

Rails and Plugins

dollars_and_cents: a Rails plugin | Archives | codablog | Coda Hale

I thought that Agile Web Development with Rails: Second Edition was going to repeat a lot of information from the first edition. I was wrong; the second edition updates a lot of techniques using conventions that have developed since the last book.

For example, one of the best ways to start a rails project is by using migrations. This book works with that and I assume even more. Personally the migrations section was well worth it. As an added benefit, I'm getting different information going through the depot example a second time because I understand how rails works and can understand better why the examples do this or that.

Quick notes: The book uses Edge Rails which I refused to install (my only problem with the book). The migrations model uses a :decimal call that is not available in rails 1.1.6 I was able to use my first rails plugin called dollars_and_cents. Radrails made the install very easy. The hard part was modifying the code to use this plugin.

Here is my notes:

Migration line: add_column :products, :price_in_cents, :integer, :default => 0

I ran 'ruby script/generate scaffold Product' which created a new products view. I used this code to modify the views and then copied them into the admin view.

list.rhtml:
<table>
<tr>
<% for column in Product.content_columns %>
<th><%= column.human_name %></th>
<% end %>
<th>Price</th>
</tr>

<% for product in @products %>
<tr>
<% for column in Product.content_columns %>
<td><%=h product.send(column.name) %></td>
<% end %>
<td><%=h number_to_currency(product.price)%></td>
<td><%= link_to 'Show', :action => 'show', :id => product %></td>
<td><%= link_to 'Edit', :action => 'edit', :id => product %></td>
<td><%= link_to 'Destroy', { :action => 'destroy', :id => product }, :confirm => 'Are you sure?', :post => true %></td>
</tr>
<% end %>
</table>

_form.rhtml (replace the last couple lines with this):
<p><label for="product_price">Price in dollars</label><br/>
<%= text_field 'product', 'price' %></p>
<!--[eoform:product]-->

show.rhtml (abridged):
<% for column in Product.content_columns %>
<p>
<b><%= column.human_name %>:</b> <%=h @product.send(column.name) %>
</p>
<% end %>

<p>
<b>Price in Dollars:</b> <%=h number_to_currency(@product.price) %>
</p>

No comments:

Post a Comment