Forum: Ruby on Rails has_and_belongs_to_many question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Be9bdbdbbe6e5dfbb1bb51729a5eab73?d=identicon&s=25 uli kunkel (Guest)
on 2007-05-30 18:43
Hi,

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.
Eb778b8bb642aa8a82c2b8b63705b6af?d=identicon&s=25 Jean-Etienne Durand (jetienne)
on 2007-05-30 19:45
Uli,

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).

Regards,
Jean-Etienne
http://www.woa.hu
241b11f59c4bcfc2ce84a43f52b30001?d=identicon&s=25 Sean Cahoon (osakaboy)
on 2007-05-31 11: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.