Forum: Ruby on Rails has_and_belongs_to_many question

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
uli kunkel (Guest)
on 2007-05-30 20:43

I have a has_and_belongs_to_many relationship between games and users in
my project. Now i want to save the rank a user had each game he played.
It seems obvious to add a field in the table linking the two holding the
rank. Only im having problems making this happen. Creating a model of
this table makes ruby think the corresponding table is game_users, and
ruby also needs an id field in this table.
Probably some really easy settings to fix this, but i cant find it
anywhere so any help would be appreciated.
Jean-Etienne D. (Guest)
on 2007-05-30 21:45

If you want to have some properties in your association, you may create
a model for that.
Remove your games_users table (I guess from your Game or User migration
file), and create a model.
Add game_id, user_id and rank in your migration file.

Then add belongs_to :user and belogns_to :game in this model. Last, add
has_many in User and Game model.

If you want to access users from Game and games from User, just add an
has_many :through (check the doc).

Sean C. (Guest)
on 2007-05-31 13:09
Jean is right. If you want to include information with your
associations, you can't use HABTM anymore. You have to make your HABTM
table into a normal table and associate the other tables with each other
":through" that table instead.
This topic is locked and can not be replied to.