Ruby-on-rails – How to do a join query in rails

rubyruby-on-rails

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?

Best Solution

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