【发布时间】:2014-02-23 18:33:25
【问题描述】:
我有以下使用 FullCalendar 显示事件的架构:
class Event < ActiveRecord::Base
has_many :event_occurrences, dependent: :destroy
def as_json(options = {})
{
:id => self.id,
:title => self.name,
:start => start_time.rfc822,
:end => end_time.rfc822,
}
end
end
class EventOccurence < ActiveRecord::Base
belongs_to :event
end
Event 对象的构成(为简洁起见,我删除了一些字段):
=> Event(id: integer, name: string, start_time: datetime, end_time: datetime)
EventOccurence 对象的构成:
=> EventOccurrence(id: integer, event_id: integer, date: datetime)
JSON 输出如下所示:
{:id=>1, :title=>"Your title", :location=>"Bermuda", :start=>"Sun, 05 Jan 2014 02:50:07 +0000", :end=>"Sun, 05 Jan 2014 02:51:46 +0000"}
我有一个单独的 EventOccurence 模型的原因是单独存储重复事件,正如this StackOverflow 帖子中所建议的那样,我也尝试创建一个单独的连接表来存储重复事件。
目前,我能够仅查询适用于 FullCalendar 的 Event 对象。但是,Associations 或 EventOccurrence 对象没有使用这个显示:
@events = Event.all.includes(:event_occurrences)
这是我目前正在尝试的:
calendar.js.erb
....
eventSources: [{
url: '/calendar/index'
}],
....
calendar_controller.erb
def index
@events = Event.all.includes(:event_occurrences)
respond_to do |format|
format.html # index.html.erb
format.json { render json: @events }
end
end
我这样做的方式是否正确?我的 EventOccurrence 模型是否需要任何其他字段?
编辑 1:
让我尽力说明我想要实现的目标:
- 我有一个包含事件的日历。
- 其中一些事件是“重复”事件。
=> 对于这些重复发生的事件,我想将它们单独存储到“加入”表中,以便在查询时可以在给定月份的参数中过滤它们。 (建议here)。
我的模型在上面,如Event 和EventOccurrence。它目前的工作方式是:
- 如果一个事件不重复发生,那么它的基本事件数据将存储在
Event模型 (:name, :start_time, :end_time) 中。 - 如果一个事件是重复发生,那么它的基本信息(
:name, :start_time, :end_time)存储在Event模型中,然后,它的所有后续事件都存储在EventOccurrence模型中(:event_id, :date)。我从EventOccurrence模型中省略了 (:start_time和:end_time),因为我假设这将由Event模型中的父级处理。
根据我上面提供的场景,存储和检索事件的最佳方式是什么?
【问题讨论】:
-
你需要得到什么结构的 json 输出?有例子吗?
-
@itsnikolay,请查看我在问题中的编辑。
-
问题是:你不能在json中得到
event_occurrences?如果是,那么您可以使用joins@events = Event.joins(:event_occurrences) -
嗨@itsnikolay,所以,你所做的工作。但是,它仅在父
Event具有EventOccurrence对象时才有效。但是,我也想收集没有EventOccurrence的Event对象。我现在完全糊涂了。我认为这是我的模型的问题。我将尽我所能在上面的编辑中阐明我想要实现的目标。
标签: ruby-on-rails json include recurring-events