0

I'm trying to make a class to populate a deals tab on my website.

Part 1. Take an items close date (CatalogItem.close_date) and use all items within 12 hours of closing. Part 2. Calculate the deal percentage by using the current price (CatalogItem.current_price) and estimated value (Item.estimated_price) <-- You'll notice they're in different tables but they're identified by an identical item_id.

I'm green in RoR, so I'm having trouble connecting this in a class, but I can make it work individually in the console:

hour_diff = (CatalogItem.last.close_date - Time.now) / 1.hour
deal_percentage = (CatalogItem.last.current_price.to_f / Item.last.estimated_price)*100   

As you can see I'm using my .last piece of data, but I want to create an array that runs through all my items, that's where my knowledge goes dry, any help would be much apreciated

jahrichie
  • 1,215
  • 3
  • 17
  • 26

1 Answers1

0

I'm assuming you are using a belongs_to, but I think what you want to do is use an instance method. This would be your model, app/models/catalog_item.rb

class CatalogItem < ActiveRecord::Base
  belongs_to :item

  def hours_remaining
    (close_date - Time.now) / 1.hour
  end

  def deal_percentage
    (current_price.to_f / item.estimated_price)*100
  end
end

Then, you could access them in a view something like this:

<table>
  <% CatalogItem.all.each do |ci| %>
    <tr>
      <td><%= ci.hours_remaining %></td>
      <td><%= ci.deal_percentage %></td>
    </tr>
  <% end %>
</table>
Josh W Lewis
  • 1,319
  • 11
  • 19
  • .last would just be the last data entered, I was just using that in the console to pull some data. I'd need to run against all data in the those tables and since the estimated price is in a different table wouldn't that muck this approach? – jahrichie Jul 03 '12 at 22:07
  • I revised my answer for you. You can pull all records into an array with CatalogItem.all. – Josh W Lewis Jul 04 '12 at 01:01
  • Pulling data from multiple tables is fine, and happens in just about every app. Rails handles it well. However, if these tables really represent the same object, it would probably be better to make one model and table. – Josh W Lewis Jul 04 '12 at 01:02
  • I actually eneded up doing most this in sql, WAAY faster! – jahrichie Jul 20 '12 at 20:48