On Apr 16, 10:10 am, Andrew S. [email protected] wrote:
defined number of subobjects of a particular type. In this situation I
don’t necessarily want to use habtm or has_many :through. The join
table just adds overhead to things like validation and ensuring that
there are not more than 2 referees attached to the game, etc.
You are going to have to add “belongs_to_many” as well as “has_two”…
if your game table has referee ids in it, then a game belongs_to a
referee (not what you would expect, but that’s the way it is). The
problem will come in when you say referee.game = somegame (or
referee.games << game) or game.referees << referee, because a referee
has_two (or five, whatever) games. Which column should these
operations reference and change in the games table? In other words,
if you assign a referee to a game, which of the already assigned
referees should be replaced? It’s going to get ugly quick: you’ll
have to have some kind of either pre-named function to do that for you
(that would be hardcoded), or pass in a block. It’s a lot of work for
a thin veneer of syntactic sugar… unless you have 10 or 20 of
something, you really just need to write the 10 lines of code. This
is probably why this feature doesn’t exist.
Either you would have to break bi-directional referencing between your
models (clearly not optimal), or write the replacement policy yourself
(what you are having to do now anyway). It’s just not something
where there is really only one correct way to do it. The same applies
to modifying habtm with a :limit parameter or something like that,
which if you had to do it some way, that’s what I would use, and throw
an exception if you try to add too many things. I.e. force the user
to take a referee away before adding if there are already two.
Here’s the proper (IMO) way to do it:
:habtm :referees do
def addreferee
(guard against too many referees)
end
#I have never tried this, but you might be able to overload
operators using this
def <<(ref)
end
end
or:
:habtm :referees, :before_add => :validate_refs
def validate_refs()
#Check count
end
In the Rails RDocs, checkout
ActiveRecord::Associations::ClassMethods.
Relevant sections are “Association Callbacks” and “Association
Extensions”. If you do decide to write a plugin, this is probably the
file to look at and mimic (probably using one of the methods above to
modity HABTM relationship with a :limit parameter).