development

Rails에서 언제 "has_many : through"관계를 사용해야합니까?

big-blog 2020. 7. 21. 07:32
반응형

Rails에서 언제 "has_many : through"관계를 사용해야합니까?


나는 그것이 무엇 has_many :through이며 언제 사용하는지 (및 방법) 이해하려고합니다 . 그러나 나는 그것을 얻지 못했습니다. Beginning Rails 3을 읽고 있으며 인터넷 검색을 시도했지만 이해할 수 없습니다.


두 모델을 가지고 말 : UserGroup.

사용자가 그룹에 속하게하려면 다음과 같이 할 수 있습니다.

class Group < ActiveRecord::Base
  has_many :users
end

class User < ActiveRecord::Base
  belongs_to :group
end

연결과 관련된 추가 메타 데이터를 추적하려면 어떻게합니까? 예를 들어, 사용자가 그룹에 가입했을 때 또는 그룹에서 사용자의 역할은 무엇입니까?

여기에서 연결을 첫 번째 클래스 객체로 만듭니다.

class GroupMembership < ActiveRecord::Base
  belongs_to :user
  belongs_to :group

  # has attributes for date_joined and role
end

이것은 새로운 테이블을 소개하고 group_id, 사용자 테이블에서 열을 제거 합니다.

이 코드의 문제점은 사용자 클래스를 사용하는 다른 모든 위치를 업데이트하고 변경해야한다는 것입니다.

user.groups.first.name

# becomes

user.group_memberships.first.group.name

이러한 유형의 코드는 짜증나 며 이와 같은 변경 사항을 도입하는 것은 고통 스럽습니다.

has_many :through 두 세계의 최고를 제공합니다.

class User < ActiveRecord::Base
  has_many :groups, :through => :group_memberships  # Edit :needs to be plural same as the has_many relationship   
  has_many :group_memberships
end

이제 일반처럼 취급 할 수 has_many있지만 필요할 때 연관 모델을 활용할 수 있습니다.

로도이 작업을 수행 할 수 있습니다 has_one.

편집 : 그룹에 사용자를 쉽게 추가

def add_group(group, role = "member")
  self.group_associations.build(:group => group, :role => role)
end

이 모델이 있다고 가정 해보십시오.

Car
Engine
Piston

자동차 has_one :engine
엔진 belongs_to :car
엔진 has_many :pistons
피스톤belongs_to :engine

자동차 has_many :pistons, through: :engine
피스톤has_one :car, through: :engine

기본적으로 모델 관계를 다른 모델에 위임하므로을 호출하는 대신 car.engine.pistons할 수 있습니다.car.pistons


ActiveRecord 조인 테이블

has_many :through and has_and_belongs_to_many relationships function through a join table, which is an intermediate table that represents the relationship between other tables. Unlike a JOIN query, data is actually stored in a table.

Practical Differences

With has_and_belongs_to_many, you don't need a primary key, and you access the records through ActiveRecord relations rather than through an ActiveRecord model. You usually use HABTM when you want to link two models with a many-to-many relationship.

You use a has_many :through relationship when you want to interact with the join table as a Rails model, complete with primary keys and the ability to add custom columns to the joined data. The latter is particularly important for data that is relevant to the joined rows, but doesn't really belong to the related models--for example, storing a calculated value derived from the fields in the joined row.

See Also

In A Guide to Active Record Associations, the recommendation reads:

The simplest rule of thumb is that you should set up a has_many :through relationship if you need to work with the relationship model as an independent entity. If you don’t need to do anything with the relationship model, it may be simpler to set up a has_and_belongs_to_many relationship (though you’ll need to remember to create the joining table in the database).

You should use has_many :through if you need validations, callbacks, or extra attributes on the join model.

참고URL : https://stackoverflow.com/questions/11600928/when-should-one-use-a-has-many-through-relation-in-rails

반응형