Question

I have some problem trying to understand when building a rails app with several models and relation ships between them...

If I take a basic example like a model Group, a model User and a model Car

class Group < ActiveRecord::Base
   has_many :users
end 
class User < ActiveRecord::Base
  belongs_to :group
  has_many :cars
end 
class Car < ActiveRecord::Base
  belongs_to :user
end

Will those relation ship statements automatically create the following functions:

  • group.users
  • user.group
  • user.cars
  • car.user

It seems that we sometimes need to have to create "references" in migration (like adding a reference toward User in Car table) but is this always required ? In this case, what is the difference of creating the migration and of adding the relationship statement in the models ? I sometimes have the feeling this is used for the same purpose.

Thanks a lot for your help,

Regards,

Luc

Was it helpful?

Solution

The association declarations are there for Rails only. You have to define the foreign keys (references) in the database, so that Rails can properly save the data.

Remember, despite all the magic, it's still backed by a relational database, so good practices there will pay off in the long run.

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