(Ruby/Rails guru’s preferably :P)
I’ve got a bit of an interesting question. Hope it’s not already answered (wait, yes I do!) but I’ve looked and couldn’t find it. (Hopefully not because it’s not possible)
I’ve got two classes (and I’d like to keep it that way) Group and Event (see below).
class Group < ActiveRecord::Base
has_and_belongs_to_many :events
end
However in my join table (group_events), I have additional columns which provide extenuating circumstances to the event… I want this information to be available on the event object. (For example, whether attendance is mandatory or not etc)
My second slightly related question is, can I not do the following:
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
I would first rewrite the
has_and_belongs_to_many, explicitly describing the relationship betweenEventand the model forGroupEvent.You can then methods within the
Eventclass to refer to the GroupEvent attributes your’e after. For some boolean:attendance_mandatoryattribute inGroupEvent, you could do something likeWith some
Eventaseand associatedGroupasg, you could now doAs for your 2nd question, I think you’re looking for a piece of what I’ve posted in the first code block above.
Every table containing data you wish to interact with should have a representative model in your application. The above meets your stated criteria (exposes the attributes of a
GroupEvent).Note: Your syntax of
class GroupEvent < Eventis used for Single Table Inheritance (you’d move the attributes likeattendance_mandatoryinto theeventstable, and use thateventstable for both a regularEventand aGroupEvent– though this is outside of the scope of this question)