Many times I have a join table serving a has_and_belongs_to_many
relationships. Say, there is a person table and a team table with a
many-to-many relationship. Fine, rails will automatically join them
through a people_teams table nicely:
person.teams<<(team)
But if I want that join table to have other attributes (like
joined_date), I can''t figure out an effective shortcut. Seems like a
common problem and I found this in the docs:
collection.push_with_attributes(object, join_attributes) - adds one to
the collection by creating an association in the join table that also
holds the attributes from join_attributes (should be a hash with the
column names as keys). This can be used to have additional attributes
on the join, which will be injected into the associated objects when
they are retrieved through the collection.
(collection.concat_with_attributes is an alias to this method).
...but when I run that like so:
person.teams.push_with_attributes(team, "joined_date" =>
Time.now.to_i), I get this error:
Track expected, got Array
Can''t get rid of the error by making the attributes hash into a hash
reference either. Next I tried making a PersonTeam model to enable a
before_save method on it to automatically record a joined_date, but
that didn''t work either. I must just be missing something unless this
is a bug. Any ideas?