ProgramingTip

Rails에서 has_one과 belongs_to의 차이점은 무엇입니까?

bestdevel 2020. 11. 3. 08:24
반응형

Rails에서 has_one과 belongs_to의 차이점은 무엇입니까?


이 질문에 이미 답변이 있습니다.

has_oneRoR의 관계 를 이해하려고합니다 .

의 나는 두 가지 모델이 가정 해 봅시다- PersonCell:

class Person < ActiveRecord::Base
  has_one :cell
end

class Cell < ActiveRecord::Base
  belongs_to :person
end

난 그냥 사용할 수 has_one :person대신 belongs_to :personCell모델?

똑같지 꼭 필요한나요?


아니요, 서로 비교할 수 몇 가지 실제 차이점이 있습니다.

belongs_to이 클래스의 테이블에 외래 키가 있음을 의미합니다. 따라서 belongs_to외래 키를 보유한 클래스에만 더 많이 있습니다.

has_one이 클래스를 참조하는 다른 테이블에 외래 키가 있음을 의미합니다. 따라서 has_one다른 테이블의 열에서 참조하는 클래스에만 도움말 수 있습니다.

이것은 잘못되었습니다.

class Person < ActiveRecord::Base
  has_one :cell # the cell table has a person_id
end

class Cell < ActiveRecord::Base
  has_one :person # the person table has a cell_id
end

그리고 이것은 또한 잘못되었습니다.

class Person < ActiveRecord::Base
  belongs_to :cell # the person table has a cell_id
end

class Cell < ActiveRecord::Base
  belongs_to :person # the cell table has a person_id
end

올바른 방법은 다음과 같습니다 ( 필드 Cell포함 된 경우 person_id).

class Person < ActiveRecord::Base
  has_one :cell # the person table does not have 'joining' info
end

class Cell < ActiveRecord::Base
  belongs_to :person # the cell table has a person_id
end

양방향 연결의 경우 하나가 필요하며 올바른 클래스로 이동해야합니다. 단방향 연결의 경우에도 어떤 연결을 사용하는지가 중요합니다.


"belongs_to"를 추가하면 양방향 연결이됩니다. 즉, 세포에서 사람을, 사람에게서 세포를 얻을 수 있습니다.

실제 차이는 없습니다. 두 접근 방식 ( "belongs_to"포함 및 제외)은 동일한 데이터베이스 스키마 (셀 데이터베이스 테이블의 person_id 필드)를 사용합니다.

요약하면 : 모델간에 양방향 연결이 필요하지 않고 "belongs_to"를 추가하지 않습니다.


둘 다 사용하면 Person 및 Cell 모델에서 정보를 얻을 수 있습니다.

@cell.person.whatever_info and @person.cell.whatever_info.

참고 URL : https://stackoverflow.com/questions/861144/difference-between-has-one-and-belongs-to-in-rails

반응형