【发布时间】:2015-02-26 23:00:39
【问题描述】:
我有多个控制器,我想将它们的一些方法放到我的侧边栏中:
habits_controller
goals_controller
valuations_controller
quantifieds_controller
users_controller
如何在不出现未定义方法错误的情况下执行此操作?
我尝试创建一个 sidebar_controller,但我应该在其中包含什么才能使其正常工作?
让我们以习惯为例,然后我可以将我学到的经验应用到我自己的其他控制器上。
摘自_sidebar.html.erb
<div id="sidebarheadingtop" class="panel-heading"><h5><b>Today</b></h5></div>
<% @habits.each do |habit| %>
<td><%= raw habit.tag_list.map { |t| link_to t.titleize, tag_path(t) }.join(', ') %></td>
<% end %>
</div>
habits_controller
class HabitsController < ApplicationController
before_action :set_habit, only: [:show, :edit, :update, :destroy]
before_action :logged_in_user, only: [:create, :destroy]
def index
if params[:tag]
@habits = Habit.tagged_with(params[:tag])
else
@habits = Habit.all.order("date_started DESC")
@habits = current_user.habits
end
end
def show
end
def new
@habit = current_user.habits.build
end
def edit
end
def create
@habit = current_user.habits.build(habit_params)
if @habit.save
redirect_to @habit, notice: 'Habit was successfully created.'
else
@feed_items = []
render 'pages/home'
end
end
def update
if @habit.update(habit_params)
redirect_to @habit, notice: 'Habit was successfully updated.'
else
render action: 'edit'
end
end
def destroy
@habit.destroy
redirect_to habits_url
end
private
def set_habit
@habit = Habit.find(params[:id])
end
def correct_user
@habit = current_user.habits.find_by(id: params[:id])
redirect_to habits_path, notice: "Not authorized to edit this habit" if @habit.nil?
end
def habit_params
params.require(:habit).permit(:missed, :left, :level, :date_started, :trigger, :target, :positive, :negative, :tag_list, :committed => [])
end
end
sidebar_controller
class SidebarController < ApplicationController
def index
@habits = current_user.habits
end
end
我还是一个初学者,所以任何帮助将不胜感激。谢谢=]
【问题讨论】:
标签: ruby-on-rails ruby methods controller sidebar