- 红宝石 1.9.2p290
- 导轨 3.1.1
我有这些模型:
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
例如:在圣诞节期间(大约整个 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)