开发者

rails model relationship and migration

开发者 https://www.devze.com 2023-02-16 21:15 出处:网络
I have some problem trying to understand when building a rails app with several models and relation ships between them...

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 &l开发者_运维技巧t; 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号