(Ruby / Rails guru最好:P)
我有一个有趣的问题。希望它还没有得到回答(等等,是的,我做了!)但我看上去却找不到它。 (希望不是因为它不可能)
我有两个班级(我想保持这种方式)小组和活动(见下文)。
class Group < ActiveRecord::Base
has_and_belongs_to_many :events
end
但是在我的连接表(group_events)中,我还有其他列为事件提供了可视的情况......我希望这些信息可以在事件对象上使用。 (例如,是否强制出勤等)
我的第二个稍微相关的问题是,我不能做以下事情:
class Event < ActiveRecord::Base
has_and_belongs_to_many :groups
end
class GroupEvent < Event
# Implies that a GroupEvent would be an Event, with all the other attributes of the group_events table minus the
# two id's (group_id, event_id) that allowed for its existence (those would just be references to the group and event object)
end
答案 0 :(得分:3)
我首先会重写has_and_belongs_to_many
,明确描述Event
与GroupEvent
模型之间的关系。
class Group < ActiveRecord::Base
has_many :group_events
has_many :events, :through => :group_events
end
class Event < ActiveRecord::Base
has_many :group_events
has_many :groups, :through => :group_events
end
class GroupEvent < ActiveRecord::Base
belongs_to :group
belongs_to :event
end
然后,Event
类中的方法可以引用您之后的GroupEvent属性。对于:attendance_mandatory
中的某些布尔GroupEvent
属性,您可以执行类似
class Event < ActiveRecord::Base
has_many :group_events
has_many :groups, :through => :group_events
def attendance_mandatory?(group)
group_events.find(group.id).attendance_mandatory?
end
end
某些Event
为e
且关联Group
为g
,您现在可以
e.attentdance_mandatory?(g)
关于你的第二个问题,我想你正在寻找我在上面第一个代码块中发布的内容。
class GroupEvent < ActiveRecord::Base
belongs_to :group
belongs_to :event
end
包含您希望与之交互的数据的每个表都应在您的应用程序中具有代表性模型。以上内容符合您声明的标准(公开GroupEvent
)的属性。
注意:您的class GroupEvent < Event
语法用于Single Table Inheritance (您可以将attendance_mandatory
等属性移至events
}表,并将events
表用于常规Event
和GroupEvent
- 尽管这超出了此问题的范围)