【问题标题】:How to stop NoMethodError when clicking #new & #edit?单击#new和#edit时如何停止NoMethodError?
【发布时间】:2015-02-28 22:01:02
【问题描述】:

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

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

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

<% @top_3_goals.each do |goal| %> 在应用程序的侧边栏中正确显示,这是从目标控制器派生的 #index @top_3_goals = @unaccomplished_goals.top_3 BUT 如果我点击链接 goals/newgoals/1/edit 我得到了可怕的:@ 987654328@!

这是一个视图细分:

我在views/layouts/application.html.erb 中使用<%= render 'sidebar/sidebar' %>views/sidebar/_sidebar.html.erb为了用<%= render 'goals/upcoming' %>views/goals/_upcoming.html.erb

views/goals/_upcoming.html.erb

<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>

views/sidebar/_sidebar.html.erb

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

目标控制器

  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 < 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

我需要在 sidebar_controller 中添加任何内容吗?我在那里尝试添加逻辑,但似乎没有任何区别。我还是个初学者,所以我在这里说的可能没有意义。现在我在 sidebar_controller 中什么都没有,因为我从那里得到的唯一视图是_sidebar.html.erb(我不太确定部分如何利用控制器)。如果我将部分_upcoming.html.erb 呈现在目标索引中(所有链接都有效),那么部分_upcoming.html.erb 工作得很好,但是如果我在_sidebar 中呈现它,我怎样才能让它工作呢?

感谢您这么久以来的耐心=]

【问题讨论】:

  • 如果侧边栏出现在所有页面上,那么您需要向填充侧边栏视图或侧边栏视图使用的所有@ 变量的每个请求(通过应用程序控制器)添加代码需要通过 ajax 向服务器发出单独的请求。每个请求只有一个控制器处于活动状态。
  • 我认为部分问题可能是对控制器方法(或“操作”)的一些混淆。一个请求,比如说对goals/new 的 GET,将由路由引擎解析并定向到一个控制器操作。必须为该视图显示的所有代码都必须包含在该操作中。希望对您有所帮助。

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


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多