views:

61

answers:

1

I have Events, Documents, and Surveys which all need to be able to link to one another, I was planning on having a linking table with four columns as follows:

link_elements{
  element1_type CHAR(1)
  element1_id INTEGER
  element2_type CHAR(1)
  element2_id INTEGER
}

The problem is I can't figure out how to make the model in RoR so that I can use the element type field to identify which table the corresponding element id belongs to (Documents, Events, or Surveys). I'm really new to Ruby and any help would really be appreciated.

A: 

I think you're just looking for the has_many and belongs_to associations.

If you have an Event model, a Document model, and a Survey model, then you can specify in their respective .rb files in the Models folder if they have or belong to the other models.

Ex: you want Surveys to belong to Documents. In Survey.rb, add the line belongs_to :document. In Document.rb, add the line has_many :surveys.

Now if you add a new "document_id" column in the Surveys table, it will look for a a Document object that corresponds to the id integer in that column.

For more info check out the Rails API.

funkymunky
Documents are stored in one table, surveys in one table, and events in yet another table. Simply adding a column to those tables would only allow me to link each element to only one other element of each type. I need to figure out how to create a table that would let me link those elements together like the one I mentioned in the original posting of the question and get Ruby to read the first column as the table identifier and the second column as the row identifier.
John Schultz
Ah okay. Then you need a has_and_belongs_to_many relationship. This associations looks for a join table that has the ids of both the objects you are associating. I haven't personally used it, so I can't give you specifics, but look here(http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html) and scroll down to the Many-to-many section. you can see what the join table looks like here(http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001836). I'm guessing you'll need 3 separate join tables: Document-Survey, Document-Event, and Event-Survey.
funkymunky