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 Has and Belongs to Many

create relationships in the model or in the migration?

Hi I want to know the difference of create relationships in the migration file and in the model file. I see you can go to the migration file and make something like this:

create_table :employees_projects do |t|
        t.belongs_to :employee, :project
        t.timestamps
    end

also you can go to a model file and add a relationship

class Project < ActiveRecord::Base
    belong_to :customer
    has_and_belongs_to_many :employees
end

I want to know the difference of creating the relationships in the migration files and in the models, I got confused in that step.

1 Answer

Maciej Czuchnowski
Maciej Czuchnowski
36,441 Points

These are two different things. The migration is only used to create, remove or modify columns in the database that you have - it modifies your db/schema.rb file when migrated. The relationships declared in the model require the relationships to already be in the database and allow you to utilize this relationship in the Rails app itself more easily. Example:

Let's say that you have two models - Tweet and User. Normally, there is no relationship between them. If you want to make one, you need to add user_id column in the tweet table in the database. To do that you create a migration that adds this column. But this is not over - you still can't use this relationship in your app by calling, for example, user.tweets (to see all tweets) or tweet.user (to see who owns the tweet). To do that, you have to declare that relationship in the model: has_many in the user model and belongs_to in the tweet model. This also tells Rails how to interpret id's in the urls.

You can also create a migration that changes the schema AND includes proper relationship in the model or models, which is more or less what your fist code snippet does.

I hope this is correct and readable :)