单击#new&时如何停止NoMethodError #编辑?

时间:2015-02-28 22:01:02

标签: ruby-on-rails ruby model-view-controller sidebar nomethoderror

我很难弄清楚如何将多个控制器的逻辑合并到侧边栏中。

例如,我想在侧边栏中有一个部分,它使用habit_controller中的@habits逻辑和一个使用来自goals_controller的@unaccomplished_goals逻辑的部分。

对于这个问题,我们只关注@unaccomplished_goals

<% @top_3_goals.each do |goal| %>在应用侧边栏中正确显示,如果我点击链接goals/new,该侧边栏来自goal_controller #index @top_3_goals = @unaccomplished_goals.top_3 goals/1/edit我得到了可怕的:undefined method each for nil:NilClass

以下是查看细分:

我在<%= render 'sidebar/sidebar' %>中使用views/layouts/application.html.erb 抓住views/sidebar/_sidebar.html.erb以使用<%= render 'goals/upcoming' %>抓取views/goals/_upcoming.html.erb

视图/目标/ _upcoming.html.erb

&#13;
&#13;
<table>
  <% @top_3_goals.each do |goal| %>
    <tr>
      <td>
        <strong>
          <%= link_to goal.name, edit_goal_path(goal) %>
        </strong>
      </td>
      <td>
        <%= goal.deadline.strftime("%m-%d-%Y") %>
      </td>
    </tr>
  <% end %>
</table>
&#13;
&#13;
&#13;

视图/侧边栏/ _sidebar.html.erb

&#13;
&#13;
<div id="sidebarsection" class="panel panel-default">
<div id="sidebarheading" class="panel-heading"><h5><b>Upcoming</b></h5></div>
  <%= render 'goals/upcoming' %>
</div>
&#13;
&#13;
&#13;

目标控制器

&#13;
&#13;
  def index
    if params[:tag]
      @goals = Goal.tagged_with(params[:tag])
    else
      @goals = Goal.all.order("deadline")
      @accomplished_goals = current_user.goals.accomplished
      @unaccomplished_goals = current_user.goals.unaccomplished
      @top_3_goals = @unaccomplished_goals.top_3
    end
  end
&#13;
&#13;
&#13;

目标模型

&#13;
&#13;
class Goal < ActiveRecord::Base
	belongs_to :user
	acts_as_taggable
	scope :accomplished, -> { where(accomplished: true) }
	scope :unaccomplished, -> { where(accomplished: false) }
	validates :name, presence: true

	scope :top_3, -> do
  order("deadline DESC").
  limit(3)
end
end
&#13;
&#13;
&#13;

我是否需要在sidebar_controller中放置任何内容?我在那里添加了逻辑,但它似乎没有任何区别。我还是个初学者,所以我在这里说的话可能毫无意义。现在我在sidebar_controller中没有任何东西,因为我从那里得到的唯一视图是_sidebar.html.erb(我不太确定部分如何利用控制器)。如果我在目标索引中渲染了部分_upcoming.html.erb,那么部分{{1}}工作得很好(链接全部工作),但如果我在_sidebar中渲染它,我怎么能让它工作?

感谢我忍受这一点=]

1 个答案:

答案 0 :(得分:1)

不应该有侧边栏控制器这样的东西,除非你打算让侧边栏成为某种iframe或者某种东西(这很奇怪)。

就像@patrickmcgraw建议的那样,我会在应用程序控制器中创建一个before_action,以确保始终设置这些变量。

class ApplicationController < ActionController::Base
  before_action :set_top_3_goals

  def set_top_3_goals
    @top_3_goals = current_user.goals.unaccomplished.top_3
  end
end