我有一个稍微复杂的查询,我想作为一个自然的ActiveRecord关系。目前我打电话@ calendar.events和@ calendar.shared_events,然后加入数组并对它们进行排序。整合是可以完成这个SQL:你会如何在ActiveRecord关系中表示这个sql查询?
SELECT calendar_events.* FROM calendar_events left outer join calendar_events_calendars on calendar_events_calendars.calendar_event_id = calendar_events.id where calendar_events.calendar_id = 2 or calendar_events_calendars.calendar_id = 2
但我不知道如何表示这是一个ActiveRecord关系。我知道我可以使用自定义的SQL查找器,但我希望能够在结果上使用范围。
目前事件属于一个日历,也通过的habtm属于许多其他日历连接表:
has_and_belongs_to_many :shared_events, :class_name => 'CalendarEvent', :order => 'beginning DESC, name'
has_many :events, :class_name => 'CalendarEvent', :dependent => :destroy, :order => 'beginning DESC, name'
任何指针将不胜感激:)
这是一个很好的问题。每个事件只属于一个日历,但可以链接到其他日历。我想我可以做一个has_many:通过并在连接表上设置某种布尔列来表明事件是否属于这个日历,但这看起来太过微妙。比事件绝对属于一个日历更好,如果有必要,也可以链接到其他事件。我明白为什么activerecord不允许这样的关系,因为它会增加新事件的问题。 – 2009-07-13 06:28:48