我在rails应用中使用event_calendar gem。 Event_calendar将以下内容添加到事件模型中,以定义日历视图的开始和结束日期。
has_event_calendar :start_at_field => 'sdate', :end_at_field => 'tdate'
其中sdate
和tdate
是模型中的字段。
但是,在我的情况下,我没有在数据库中存储结束日期。结束日期基于持续时间字段计算,即sdate + duration。我在其他地方计算结束日期没有问题,但似乎无法为event_calendar设置它。
基本上,我需要做
has_event_calendar :start_at_field => 'sdate', :end_at_field => '[event.sdate]+[event.duration]'
但一直无法找出正确的语法。
我一直在努力解决这个问题。感谢帮助我们了解其工作原理。
谢谢!
修改
有问题的模型如下:
# == Schema Information
# Schema version: 20110607040735
#
# Table name: schedules
#
# id :integer not null, primary key
# sdate :date
# tdate :date
# duration :integer
# created_at :datetime
# updated_at :datetime
#
class Schedule < ActiveRecord::Base
attr_accessible :sdate, :tdate, :duration
has_event_calendar :start_at_field => 'sdate', :end_at_field => calculated_tdate
scope :default, :order => 'schedules.sdate ASC'
def calculated_tdate
self.sdate+self.cruise.duration
end
end
但这会产生错误
undefined local variable or method `calculated_tdate' for #<Class:0x10b62cb98>
答案 0 :(得分:0)
这取决于宝石的工作方式。如果它真的要查询数据库,你需要将这些数据存储在数据库中,但是如果它只接受调用给定方法接受该属性是ActiveRecord生成的方法,你可以在模型中手动定义这样的方法:
def tdate
self.sdate+self.duration
end
试一试......
关于你的问题:它是一个数据库设计原则,不存储数据库中的数据,只要没有其他选择,就可以从数据库中已有的其他字段计算出来!
答案 1 :(得分:0)
您只需致电
即可object.calculate_tdate
获取结束日期
答案 2 :(得分:0)
在与event_calendar的开发人员讨论这个问题时,似乎目前无法使用计算的结束日期。该插件依赖于在基础表中指定结束日期列。我确信该插件可以被黑客攻击以提供所需的行为。如果我在这方面取得任何进展,我会添加更多。感谢所有给出建议的人。