简体   繁体   English

Ruby on Rails和实例变量中的单个整体

[英]Ruby on Rails and single entires in instance variables

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. 我正在尝试在Rails中构建一个小型应用程序,我有一些条目,但是我试图以一种非常小的方式在数据上构建一些统计信息。

In my controller I have @entries in an instance variable for the main data feed. 在我的控制器中,我在主数据供稿的实例变量中有@entries。 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. 但是我收到未定义的方法“每个”,我猜是因为@best_day设置为仅具有第一个条目,在我看来,我告诉Rails我希望它包含多个条目和循环超过它。 (I've tested this by changing .first to .all and I get all the results). (我已经通过将.first更改为.all进行了测试,得到了所有结果)。

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. 我的方法感觉不太“滑轨”,希望这有意义并且有人可以提供帮助。

You just need to do this: Your best day is: <%= @best_day.Date %>. 您只需要这样做: Your best day is: <%= @best_day.Date %>.

On a different note, please use lowercase attribute names if possible. 另外,请尽可能使用小写的属性名称。 Your attributes look like class names. 您的属性看起来像类名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM