views:

53

answers:

2

I know that if I name a column in a table "othertablename_id" rails will know to use that column for a belongs_to or other relation. If I want to have multiple id's from the same table, obviously this won't work, because I would have duplicate column names. What is the best way to build a table that relates two rows from the same table? As in an Appointment table that relates exactly two Users.

A: 

A model like:

Appointment 
=================
source_user_id
object_user_id

would help?

EDIT Reading the rails bible at page 361, I extracted this:

Many-to-Many Relationships

...A product can belong to many categories, and each category may contain multiple products. This is an example of a many-to-many relationship. It’s as if each side of the relationship contains a collection of items on the other side.

alt text

In Rails we express this by adding the has_and_belongs_to_many declaration to both models. From here on in, we’ll abbreviate this declaration to “habtm.” Many-to-many associations are symmetrical—both of the joined tables declare their association with each other using “habtm.”

Within the database, many-to-many associations are implemented using an intermediate join table. This contains foreign key pairs linking the two target tables. Active Record assumes that this join table’s name is the concatenation of the two target table names in alphabetical order. In our example, we joined the table categories to the table products, so Active Record will look for a join table named categories_products.

So, I think that all you have to do, is to use the has_and_belongs_to_many declaration.

eKek0
then how do i tell rails to use those columns in the relations. (belongs_to :user, PROBABLY SOMETHING HERE RIGHT?)
Joe Cannatti
thanks, and what you're saying is true, but it does not solve the problem I had in mind. I need to have the two rows that are referred to be distinguished as separate properties. Again, thanks though.
Joe Cannatti
+1  A: 

Ah I've got it

belongs_to :user_1, :class_name => "User"
belongs_to :user_2, :class_name => "User"

will use columns user_1_id and user_2_id respectively. The columns should be named something more descriptive of course, but it is quite simple.

Joe Cannatti