views:

815

answers:

4

Say I have two tables, a master list of students containing personal info, and a list of student enrollments in classes. The two tables share a common column, which is a string uniquely identifying the student, but it is not the primary key.

Say I want to display all the enrollments on a page, along with some of the personal data from the student (say perhaps hometown).

I understand that it would be a has_many relationship. The master list record has many enrollments. An enrollment belongs to a student.

class Student < ActiveRecord::Base
    has_many :enrollments
end

class Enrollment < ActiveRecord::Base
   belongs_to :student
end

Is this the correct relationship between the two, and if so, how do I do a join query against the shared column?

+5  A: 

Ideally, Rails is expecting the following columns:

Student table:
- id

Enrollment table:
- student_id

In doing so, your relationship should work.

Then to try it out, drop into the Rails console and play around:

@student = Student.first
@student.enrollments

Take a look at this great Rails reference on using associations:

http://guides.rubyonrails.org/association_basics.html

mwilliams
I guess you meant "students" and "enrollments" tables, not "Student table" and "Enrollment table".
Adam Byrtek
As a convention the model in Active Record is a singular and it will map out to a table name which is plural.
allesklar
Is it possible to override this default behavior (id and _id?)
Stephen Cox
Yes, you can assign the primary key of a model using "set_primary_key" in your model. See the following Wiki entry on how to do so: http://wiki.rubyonrails.org/rails/pages/howtouselegacyschemas
mwilliams
Exactly what I wanted. Thank you!
Stephen Cox
Please mark as answered if you're done here, thanks! :)
mwilliams
A: 

What mwilliams says plus make sure you want a many to many association when you follow the guide.

allesklar
A: 

The joined query is done automatically by association through ActiveRecord.

cnicolaou
+3  A: 

Yes ActiveRecord will manage the relationships for you, but you can also specify the join when searching for a condition in the relationship. For example:

User.find(:all, :joins => :phone_numbers, :conditions => { :phone_numbers => {:name => 'business'} })

Note though using a hash for the conditional declaration is only in Rails 2.2

But most of the time just using the ActiveRecord relationships with has_many should be just fine and as mentioned in above answers you would call the object using as if it was directly on the model... @student.enrollments

Tim K.