Problems With or Alternative To Unidirectional has_and_belongs_to_many
association
I have two components to my application, for the most part, data
entry/tracking and data reporting.
I have a basic data tracking object, let's call it Meter:
class Meter < ActiveRecord::Base
has_many :activity_records
end
I have a collection of different reporting objects, like tabular reports,
charts, widgets, etc. All of these objects, per user configuration, refer
to a collection of Meters as data sources.
I model this relationship as has_and_belongs_to_many, through a join
table: a Widget has many Meters; Meters can be referenced by many Widgets.
class Widget < ActiveRecord::Base
has_and_belongs_to_many :meters
end
Now, I don't think Meters actually need to know which reporting objects
reference them. A Meter should be able to exist blithely, collecting data
and (through a Service object) responding to data requests. I should
never, ever, refer to @meter.widgets.
So, do I need, in the Meter model, to declare half a dozen different habtm
relationships for all the different reporting objects?
Concrete Questions:
1. Are there unintended consequences from omitting the habtm declaration
on Meters?
2. Is there a better way to design this relationship?
With regard to the second question, I have played with the concept of a
MeterSet but found it a bit over-engineered:
class Widget < ActiveRecord::Base
has_one :meter_set, as: :requester
has_many :meters, through: :meter_set
end
class MeterSet < ActiveRecord::Base
belongs_to :requester, polymorphic: true
has_and_belongs_to_many :meters
end
I've moved the location of the join from one model to another... and I
suppose I've reduced the number of tables in my application, overall?
No comments:
Post a Comment