(最好是 Ruby/Rails 大师 :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
最佳答案
我会先重写 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 属性。对于一些 bool 值 :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
- 尽管这超出了本文的范围问题)
关于mysql - 事件记录。包括来自连接表的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11387242/