【发布时间】:2015-03-01 18:36:25
【问题描述】:
<% tag_cloud Habit.tag_counts, %w{m} do |tag, css_class| %>
<%= link_to tag.name, taghabits_path(tag.name), class: css_class %>
<% end %>
上面的代码列出了所有习惯标签。但是如何让它只列出今天有习惯:committed 的标签呢?
在习惯中,_form <%= f.collection_check_boxes :committed, Date::DAYNAMES, :downcase, :to_s %> 为用户提供了他在哪天 :committed 执行他的习惯的选项。
[ ] Sunday [ ] Monday [ ] Tuesday [ ] Wednesday [ ] Thursday [ ] Friday [ ] Saturday
习惯模型
class Habit < ActiveRecord::Base
belongs_to :user
before_save :set_level
acts_as_taggable
serialize :committed, Array
def levels
committed_wdays = committed.map { |day| Date::DAYNAMES.index(day.titleize) }
n_days = ((date_started.to_date)..Date.today).count { |date| committed_wdays.include? date.wday }
case n_days
when 0..9
1
when 10..24
2
when 25..44
3
when 45..69
4
when 70..99
5
else
"Mastery"
end
end
protected
def set_level
self.level = levels
end
end
习惯控制者
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
由于这段代码是在侧边栏中呈现的,我认为我们必须将控制器逻辑添加到 ApplicationController,就像我对 set_top_3_goals 所做的那样。
应用程序控制器
class ApplicationController < ActionController::Base
before_action :set_top_3_goals
protect_from_forgery with: :exception
include SessionsHelper
def set_top_3_goals
@top_3_goals = current_user.goals.unaccomplished.top_3 if logged_in?
end
private
# Confirms a logged-in user.
def logged_in_user
unless logged_in?
store_location
flash[:danger] = "Please log in."
redirect_to login_url
end
end
end
视图/布局/_sidebar.html.erb
<div id="sidebarsectiontop" class="panel panel-default">
<div id="sidebarheadingtop" class="panel-heading"><h5><b>Today</b></h5></div>
<%= render 'habits/today' %>
</div>
<div id="sidebarsection" class="panel panel-default">
<div id="sidebarheading" class="panel-heading"><h5><b>Upcoming</b></h5></div>
<%= render 'goals/upcoming' %>
</div>
非常感谢您的宝贵时间 =]
【问题讨论】:
标签: ruby-on-rails ruby tags sidebar acts-as-taggable-on