使用自连接关联来记录事件发生的最佳方式
我有这个工作 Rails 事件模型,它有一些自连接关联来查找事件的任何发生。它有一些自定义 getter,可以在任何事件发生时返回 main_events 标题和描述。
有没有更有效的方法在 Rails 中做到这一点?主要事件也应该包含在事件中吗?
例如,当迭代特定事件发生时,主要事件日期也应该显示。
class Event < ActiveRecord::Base
# linked_event:integer name:string description:text date:datetime
has_many :occurrences, :class_name => "Event", :foreign_key => "linked_event"
belongs_to :main_event, :class_name => "Event", :foreign_key => "linked_event"
def name
return Event.find(self[:linked_event]).name if self[:linked_event]
return self[:name]
end
def description
return Event.find(self[:linked_event]).description if self[:linked_event]
return self[:description]
end
end
I have this working rails Event model which has some self join associations to find any occurrences of an event. It has some custom getters which returns the main_events title and description on any occurrence.
Is there a more efficient way of doing this in rails? and Should the main event be included inside the occurrences as well?
For example when iterating through a specific events occurrences, the main event date had ought to be displayed too.
class Event < ActiveRecord::Base
# linked_event:integer name:string description:text date:datetime
has_many :occurrences, :class_name => "Event", :foreign_key => "linked_event"
belongs_to :main_event, :class_name => "Event", :foreign_key => "linked_event"
def name
return Event.find(self[:linked_event]).name if self[:linked_event]
return self[:name]
end
def description
return Event.find(self[:linked_event]).description if self[:linked_event]
return self[:description]
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
就我个人而言,我会把这两个类分开;有一个包含名称和描述的
Event
模型,以及一个包含日期时间的Occurrence
模型。然后Event has_many :occurrences
当你得到一个
Event
时,你会检查它是否已经存在于数据库中;如果是这样,您只需创建一个新的Occurrence
,否则您将创建Event
和单个Occurrence
。像这样的东西(调整使其工作 - 我还没有测试过!):
Personally, I'd split the two classes up; have an
Event
model which carries the name and description, plus anOccurrence
model with the datetime. ThenEvent has_many :occurrences
When you get an
Event
, you check to see if it already exists in the DB; if so you just create a newOccurrence
, otherwise you create theEvent
and a singleOccurrence
.Something like this (adjust so that it works - I haven't tested it!):