Created
July 9, 2013 18:22
-
-
Save voleoo/5959830 to your computer and use it in GitHub Desktop.
has_one или belongs_to
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Все просто, объясню на примере: | |
Представим следующую ситуацию, у нас есть юзеры, а у каждого юзера есть 1 проект. | |
В бд это будет так: | |
таблица users ( id, ... ) | |
таблица projects ( id, user_id, ... ) | |
Нам надо написать такой код: | |
class Project < ActiveRecord::Base | |
belongs_to :user | |
end | |
class User < ActiveRecord::Base | |
has_one :project | |
end | |
а если структура таблиц будет такая: | |
таблица users ( id, project_id, ... ) | |
таблица projects ( id, ... ) | |
тогда все наоборот: | |
class Project < ActiveRecord::Base | |
has_one :user | |
end | |
class User < ActiveRecord::Base | |
belongs_to :project | |
end | |
Если модель содержит foreign key (user_id),тогда belongs_to |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment