【发布时间】:2015-03-05 22:51:04
【问题描述】:
我们怎样才能使 layouts/_stats.html.erb 在侧边栏中工作,显示在所有页面上:
<b><center>Average</center></b>
<ul>
<li>
<% @averaged_quantifieds.each do |averaged| %>
<% averaged.statsresults.each do |result| %>
<%= result.date_value.strftime("%b") %>:
<%= link_to edit_quantified_path(averaged) do %>
<b><%= raw averaged.tag_list.map { |t| link_to t.titleize, tagquantifieds_path(t) }.join(', ') %></b><% end %>
<%= result.result_value %>
<%= averaged.metric %>
</li>
</ul>
<% end %>
<% end %>
<b><center>Instance</center></b>
<ul>
<% @instance_quantifieds.each do |instance| %>
<% instance.statsresults.each do |result| %>
<%= result.date_value.strftime("%b %d") %>:
<%= link_to edit_quantified_path(instance) do %>
<b><%= raw instance.tag_list.map { |t| link_to t.titleize, tagquantifieds_path(t) }.join(', ') %></b><% end %>
<%= result.result_value %>
<%= instance.metric %>
</ul>
<% end %>
<% end %>
没有收到此错误:undefined method "statsresults" for #<Quantified:0x007ff739b42728> 由 <% averaged.statsresults.each do |result| %> 生成
结果属于量化的,正如您在下面看到的,我正在尝试使用范围将大量潜在的:results 限制为最新的:
class Result < ActiveRecord::Base
belongs_to :user
belongs_to :quantified
scope :stats, -> do
order("date_value").
limit(1)
end
end
class Quantified < ActiveRecord::Base
belongs_to :user
has_many :results #correct
accepts_nested_attributes_for :results, :reject_if => :all_blank, :allow_destroy => true #correct
scope :averaged, -> { where(categories: 'Averaged') }
scope :instance, -> { where(categories: 'Instance') }
validates :categories, :metric, presence: true
acts_as_taggable
CATEGORIES = ['Averaged', 'Instance']
end
class ApplicationController < ActionController::Base
before_action :load_todays_habits
before_action :set_top_3_goals
before_action :randomize_value
before_action :set_stats
protect_from_forgery with: :exception
include SessionsHelper
def set_top_3_goals
@top_3_goals = current_user.goals.unaccomplished.top_3 if current_user
end
def randomize_value
@sidebarvaluations = current_user.valuations.randomize if current_user
end
def set_stats
@quantifieds = Quantified.joins(:results).all
@averaged_quantifieds = current_user.quantifieds.averaged
@instance_quantifieds = current_user.quantifieds.instance
@statsresults = current_user.results.stats
end
感谢您的帮助,如果您有时间,我还可以帮助解决另一个范围问题:https://stackoverflow.com/questions/28863999/how-to-automate-into-method
【问题讨论】:
-
你的哪一行是失败的——只是为了更多的上下文?
-
@patrick
-
我很难理解
statsresults是Quantifieds的一种方法。@statsresults只是在您的应用程序控制器中设置的一个实例。我错过了什么吗? -
这是我对这个抱歉@patrick 的尝试,我仍在努力掌握这一切。我希望它是一种结果方法,以便每次量化时只有最新的结果会显示在侧边栏中,但可能有与用户一样多的量化。该方法还必须在应用程序控制器中,因为侧边栏将显示在所有页面上。
averaged.results.each在索引中工作,所以我试图让averaged.statsresults.each在侧边栏中工作以完成上述特定目的。 -
您可以尝试将
averaged.statsresults.each移动到它自己的块中,然后尝试statsresults.each do |stat|吗?此外,您应该在statsresults中添加一个下划线以使其成为stats_results以提高可读性。此外,您的缩进使其有点难以理解。继续努力!
标签: ruby-on-rails ruby model-view-controller scope sidebar