【发布时间】: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/new 或 goals/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