单击#new&#edit时如何停止NoMethodError?
我很难弄清楚如何将多个控制器的逻辑合并到侧边栏中。
例如,我想在侧边栏中有一个部分,它使用@habits
逻辑和一个使用来自goals_controller的@unaccomplished_goals
逻辑的部分。
对于这个问题,我们只关注@unaccomplished_goals
。
在应用程序的侧边栏中正确显示,它来自goals_controller #index
@top_3_goals = @unaccomplished_goals.top_3
但是如果我点击链接目标/ new或目标/ 1 /编辑我得到可怕的: undefined method each for nil:NilClass
!
这是一个视图细分:
我在views/layouts/application.html.erb
使用来抓取
views/sidebar/_sidebar.html.erb
,以便使用来抓住
views/goals/_upcoming.html.erb
意见/目标/ _upcoming.html.erb
视图/侧边栏/ _sidebar.html.erb
目标控制器
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
目标模型
class Goal { where(accomplished: true) } scope :unaccomplished, -> { where(accomplished: false) } validates :name, presence: true scope :top_3, -> do order("deadline DESC"). limit(3) end end
我需要在sidebar_controller中放置任何东西吗? 我在那里添加逻辑,但它似乎没有任何区别。 我还是初学者,所以我在这里说的话可能毫无意义。 现在我在sidebar_controller中什么也没有,因为我从那里得到的唯一一个视图是_sidebar.html.erb
(我不太确定部分是如何使用控制器的)。 部分_upcoming.html.erb
完美地工作,如果我在目标索引(链接全部工作)中呈现它,但如果我在_sidebar中呈现它,我怎么能让它工作?
谢谢你忍受我这一点=]
不应该有侧边栏控制器这样的东西,除非你打算让侧边栏成为某种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