Question

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

Was it helpful?

Solution

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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top