Question

I'm trying to build a small application in rails, I have some entries but I trying to build some stats on the data in a very small way.

In my controller I have @entries in an instance variable for the main data feed. But I'd like to just show what the best day was based on the highest number of visitor. So I've added the following to my controller.

class EntriesController < ApplicationController
  def index
    @entries = Entry.order(Date: :desc)
    @best_day = Entry.order(Visitors: :asc).first
  end
end

Then in my view I'm trying to get hold of the single entry as follows:

<% @best_day.each do |entry| %>
  Your best day is: <%= entry.Date %>.
<% end %>

But I receive undefined method `each', I'm guessing the is because @best_day is set to only have the first entry, and in my view I'm telling rails that I'm expecting it to contain more than one entry and loop over it. (I've tested this by changing .first to .all and I get all the results).

But I'm struggling to understand how to best call this information in my view and whether having this information in an instance variable is even the best way of getting the information?

My method doesn't feel very 'rails', hope this makes sense and someone can help.

Was it helpful?

Solution

You just need to do this: Your best day is: <%= @best_day.Date %>.

On a different note, please use lowercase attribute names if possible. Your attributes look like class names.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top