2

Imagine a roster of characters in a game.

I need to let users vote on which character counters which character and be able to save that in the database.

Batman is strong against Superman

Batman is strong against Joker

Batman is weak against The Riddler


How can I model this relationship between two of the same type of models? Batman, Superman and Joker are all part of the same Model type Superhero.

If I were to create this same system on something like ASP.Net MVC, I would create a table called Counterpicks and have two fields source_id and target_id as int fields and use them as foreign keys towards the Superhero table. Do I need to create a Counterpick model in RoR?

Any suggestions?

4

2 回答 2

3

Take a look at the paragraph on Self Joins in A Guide to Active Record Associations (Rails Guides). What you need is also a self join.

The difference between your case and the example on Rails Guides is that you need a many-to-many relationship inside the Superhero model, while the example shows a has_many type of relationship.

Both kinds of many-to-many associations in Rails (has_and_belongs_to_many and has_many through) need a join table in the database. The Counterpicks table you mentioned is precisely a join table.

In your case it's going to end up looking a bit like this:

class Superhero < ActiveRecord::Base
  has_and_belongs_to_many :losers, :class_name => "Superhero", :foreign_key => "winner_id"
  has_and_belongs_to_many :winners, :class_name => "Superhero", :foreign_key => "loser_id"
end
于 2013-03-30T22:03:34.970 回答
0

You can use your proposed table model and use the foreign key. Have a look at http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many

于 2013-03-30T19:51:15.700 回答