Topic: Cleaning this mess up

I would like to display the last purchase made by a buyer.  Here is what I have right now, it works but is very messy.  I also am trying to have it sort by the event start time which is a datetime field.  Any ideas?

<% for person in @people %>
<%= person.name %>
<% if person.purchases.find(:last) %>
<%= person.purchases.last.ticket_type.event.name %>
<%= person.purchases.last.ticket_type.event.start_time %><br />
<% end %>
<% end %>

Last edited by ladellinc (2009-01-30 00:13:30)

Re: Cleaning this mess up

Hmm I'm not sure if I can help you much. If you aren't eager loading you should probably be doing that ":include => :purchases"

Also here is a little tip I got from lazylester (another forum member)

lazylester wrote:

Just one more little DRY tip... whenever a model has a "name" attribute, I define a to_s method to return the name (def to_s; name; end). It saves typing in your views and cleans them up just a little bit more.

Another thing if you add "-" to your embedded ruby statements the actual generated view will look nicer. With this your code would look like:
<%- for person in @people -%>
  <%= person %>
  <%- if person.purchases.find(:last) -%>
    <%= person.purchases.last.ticket_type.event %>
    <%= person.purchases.last.ticket_type.event.start_time %>
  <%- end -%>
<%- end -%>

Sorry without knowing more that's as best as I can do

Re: Cleaning this mess up

How is the last purchase defined? Currently looks like its just the purchase with the highest ID.

Where does the sorting by date fit in?

And what version of Rails are you on?

Rob Anderton
TheWebFellas