Question

I understand the concept of relational databases, primary/foreign keys, etc, however, I'm having trouble seeing the actual result of setting these properties up in my models. Do they generate helper functions or something similar? or do they simply work on a database level?

For example, if I have these two models (other properties omitted)

class Course < ActiveRecord::Base
  has_and_belongs_to_many :schedules
  has_many :sections
end

class Section < ActiveRecord::Base
  belongs_to :course
end

I could simply get all sections for any given course like this:

Section.where(course_id: 1234)

However, I could do this without having set up the relations at all. So my question is: Why do we do this?

Was it helpful?

Solution

Adding these methods let's you do things like this:

Section.find(5).course  # <== returns a 'Course' model instance

Also it let's you join your queries more easily:

Section.joins(:course).where(course: {name: "English"})  # <== returns sections who have the 'english' course

Neither of these would be possible if you didn't set up the relations in the model.

Similarly:

Course.find(8).sections # returns an array of sections with 'course_id = 8'

It makes your calls more semantic, and makes things easier from a programmatic perspective :)

OTHER TIPS

Relations are applied on instances of an object. So, these relations allow you to get related objects to an instance of another.

For example, say you have an instance of Section (called @section). You'd be able to get all Course objects for that section by doing:

@section.course if you have belongs_to :course set up.

Similarly, if you have an instance of Course, you can get all Section objects for that Course with:

@course.sections if you have has_many :sections.

TL;DR - these are helper scopes for instance variables of Course and Section.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top