0
  • 红宝石 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)
4

3 回答 3

1

我要做的是在庆祝活动表中创建一个“名称”字段,然后使用假期 gem来确定特定日期是否有假期。

Holdays.on(Date.today)

这将返回一个哈希列表:每个哈希都有一个名称键。然后您可以使用它来查找正确的 Festivity 对象current_festival = Festivies.where(:name => Holdays.on(Date.today)[0][:name])并从那里获取食谱:current_festival.recipes

于 2012-04-24T16:12:39.407 回答
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
于 2012-04-24T04:21:50.383 回答
0

这假定starts_atends_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
于 2012-04-24T16:47:20.763 回答