我有这些模特:
class Recipe < ActiveRecord::Base
belongs_to :festivity
end
class Festivity < ActiveRecord::Base
has_many :recipes
end
我在“食谱”表中有以下字段:
festivity_id
“庆祝活动”表格中的以下日期时间字段:
starts_at
ends_at
如何根据庆祝日期显示内容?
我开始以这种静态方式思考:
class PagesController < ApplicationController
def home
@recipes_by_festivities = Recipe.where(:festivity_id => 4).all(:order => 'RAND()', :limit => 8)
end
end
例如:在Xmas期间(约12月份),我想显示一个festivity_id = 1的食谱列表。在感恩节期间,我想要一个festivity_id = 4的食谱列表。
我清楚了吗?如果我没有,请告诉我。解
@current_festivity = Festivity.find(:last, :conditions => ["? between starts_at AND ends_at", Time.utc(0,Time.now.month,Time.now.day,0,0,0)])
@recipes_by_festivities = Recipe.where(:festivity_id => @current_festivity).all(:order => 'RAND()', :limit => 8)
答案 0 :(得分:1)
我要做的是在庆祝活动表格中创建一个“名称”字段,然后使用holidays gem确定特定日期是否有假期。
Holdays.on(Date.today)
将返回哈希列表:每个哈希都有一个名称密钥。然后你可以使用它来查找正确的Festivity对象current_festival = Festivies.where(:name => Holdays.on(Date.today)[0][:name])
并从那里获得食谱:current_festival.recipes
答案 1 :(得分:0)
由于您希望通过庆祝活动找到食谱,您可以这样做:
def home
festivity_today = some_custom_festivity_lookup(Time.now)
if !festivity_today.nil?
@recipes = Recipe.where(festivity_id: festivity_today.id).limit(8)
else
@recipes = Recipe.limit(8)
end
end
答案 2 :(得分:0)
这假定starts_at
和ends_at
保存在同一年(0),除非期间是两年中(例如圣诞节时间):在这种情况下, ends_at
年必须为1。
Festivity.create(name: 'Christmas time', starts_at: Time.utc(0,12,25,0,0,0), ends_at: Time.utc(1,1,6,23,59,59))
Festivity.create(name: 'Ferragosto', starts_at: Time.utc(0,8,15,0,0,0), ends_at: Time.utc(0,8,15,23,59,59))
Recipe.create(festivity: Festivity.find_by_name('Periodo natalizio'))
Recipe.create(festivity: Festivity.find_by_name('Ferragosto'))
# Searching for festivities today
Recipe.includes(:festivity).where(['? BETWEEN festivities.starts_at AND festivities.ends_at', Time.utc(0,Time.now.month,Time.now.day,12,0,0)]).all
# Searching for festivities on 15 August (in Italy there is a festivity that is called Ferragosto)
Recipe.includes(:festivity).where(['? BETWEEN festivities.starts_at AND festivities.ends_at', Time.utc(0,8,15,12,0,0)]).all
# Searching for festivities on 28 December
Recipe.includes(:festivity).where(['? BETWEEN festivities.starts_at AND festivities.ends_at', Time.utc(0,12,28,12,0,0)]).all
这是一个函数的可能实现:
def recipes_on(day, month)
Recipe.includes(:festivity).where(['? BETWEEN festivities.starts_at AND festivities.ends_at', Time.utc(0,month,day,12,0,0)]).all
end