Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby ActiveRecord Basics Migrations and Relationships Relationships

Antoine Boillot
Antoine Boillot
10,466 Points

ActiveRecord : database relationship setup vs foreign keys setup ?

Hi All,

In the ActiveRecord courses, Migration section, Hampton is setting up the following table as below :

class CreateTimeEntries < ActiveRecord::Migration
  def change
    create_table :time_entries do |t|
        t.float :time
        t.belongs_to :customer
        t.belongs_to :employee
        t.timestamps
    end
  end
end

He then defines in the relevant model their relationship with already existing tables, see below :

class TimeEntry < ActiveRecord::Base
    belongs_to :customer
    belongs_to :employee
end

Aren't those lines redondant ? Could we avoid typing one or the other ?

#in table setup
t.belongs_to :customer
t.belongs_to :employee

#in the relevant model
belongs_to :customer
belongs_to :employee

Complementary question : If the lines in the table setup are here to defines foreign keys, how come then that we need to define the relationship in the model as well? I thought foreign keys were by themselves defining such relationship.

Hope I'm clear.

Thanks a lot for your help !

1 Answer

Maciej Czuchnowski
Maciej Czuchnowski
36,441 Points

The belongs_to in the migration is not the same thing as the belongs_to in the model. In the migration it adds the _id column of the associated model (it's the same as writing add_reference :time_entries, :customer). When used in the model, the belongs_to association lets you streamline some code. This - 1 Why Associations? - explains it nicely:

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