수색…


belongs_to

belongs_to 연관은 다른 모델과 일대일 연결을 설정하므로 선언 모델의 각 인스턴스는 다른 모델의 한 인스턴스에 "속합니다".

예를 들어 응용 프로그램에 사용자와 게시물이 포함되어 있고 각 게시물을 정확히 한 명의 사용자에게 할당 할 수있는 경우 게시 모델을 다음과 같이 선언하십시오.

class Post < ApplicationRecord
  belongs_to :user
end

그러면 테이블 구조에서

create_table "posts", force: :cascade do |t|
  t.integer  "user_id",  limit: 4
end

has_one

has_one 연관은 다른 모델과 일대일 연결을 설정하지만 다른 의미를 갖습니다. 이 연관은 모델의 각 인스턴스가 다른 모델의 하나의 인스턴스를 포함하거나 보유하고 있음을 나타냅니다.

예를 들어, 응용 프로그램의 각 사용자가 하나의 계정 만 갖고 있다면 다음과 같이 사용자 모델을 선언하십시오.

class User < ApplicationRecord
  has_one :account
end

액티브 레코드에서 has_one 관계가있을 때 액티브 레코드는 하나의 레코드 만 외래 키와 함께 존재하도록합니다.

이 예에서는 계정 테이블에서 특정 user_id가있는 레코드가 하나만있을 수 있습니다. 동일한 사용자에 대해 하나 이상의 계정을 연결하려고하면 이전 항목의 외래 키를 null (고아로 만들기)로 만들고 새 항목을 자동으로 만듭니다. 일관성을 유지하기 위해 새 항목에 대한 저장이 실패하더라도 이전 항목을 null로 만듭니다.

user = User.first
user.build_account(name: "sample")
user.save   [Saves it successfully, and creates an entry in accounts table with user_id 1]
user.build_account(name: "sample1")  [automatically makes the previous entry's foreign key null]
user.save  [creates the new account with name sample 1 and user_id 1]

많이있다

has_many 연관은 다른 모델과 일대 다 연결을 나타냅니다. 이 연관은 일반적으로 belongs_to 연관의 다른쪽에 위치합니다.

이 연관은 모델의 각 인스턴스에 다른 모델의 인스턴스가 0 개 이상 있음을 나타냅니다.

예를 들어 사용자와 게시물이 포함 된 응용 프로그램에서 사용자 모델은 다음과 같이 선언 될 수 있습니다.

class User < ApplicationRecord
  has_many :posts
end

Post 의 테이블 구조는 belongs_to 예제와 동일하게 유지됩니다. 반대로 User 는 스키마를 변경할 필요가 없습니다.

User 대해 게시 된 모든 게시물 목록을 가져 오려면 다음을 추가 할 수 있습니다 (즉, 연결 개체에 범위를 추가 할 수 있음).

class User < ApplicationRecord
  has_many :published_posts, -> { where("posts.published IS TRUE") }, class_name: "Post"
end

다형성 연관성

이러한 유형의 연관은 ActiveRecord 모델이 둘 이상의 종류의 모델 레코드에 속하게합니다. 일반적인 예 :

class Human < ActiveRecord::Base
  has_one :address, :as => :addressable
end

class Company < ActiveRecord::Base
  has_one :address, :as => :addressable
end

class Address < ActiveRecord::Base
  belongs_to :addressable, :polymorphic => true
end

이 연결이 없으면 주소 테이블에 이러한 모든 외래 키가 있지만이 시나리오의 주소는 하나의 엔터티 (Human 또는 Company)에만 속할 수 있기 때문에 하나의 값만 가질 수 있습니다. 다음과 같이 보입니다.

class Address < ActiveRecord::Base
  belongs_to :human
  belongs_to :company
end

has_many : through 연결

has_many :through 연관은 종종 다른 모델과 다 many-to-many 연결을 설정하는 데 사용됩니다. 이 연관은 선언 모델이 세 번째 모델을 진행함으로써 다른 모델의 인스턴스가 0 개 이상 일치 할 수 있음을 나타냅니다.

예를 들어 환자가 의사를 만날 약속을하는 의료 행위를 생각해보십시오. 관련 협회 선언은 다음과 같이 보일 수 있습니다.

class Physician < ApplicationRecord
  has_many :appointments
  has_many :patients, through: :appointments
end

class Appointment < ApplicationRecord
  belongs_to :physician
  belongs_to :patient
end

class Patient < ApplicationRecord
  has_many :appointments
  has_many :physicians, through: :appointments
end

has_one : through 연결

has_one :through association은 다른 모델과 one-to-one 연결 one-to-one 설정합니다. 이 연관은 선언 모델이 세 번째 모델을 진행함으로써 다른 모델의 한 인스턴스와 일치 할 수 있음을 나타냅니다.

예를 들어 각 supplier 에 하나의 account 이 있고 각 계정이 하나의 계정 기록과 연결되어 있다면 공급 업체 모델은 다음과 같이 보일 수 있습니다.

class Supplier < ApplicationRecord
  has_one :account
  has_one :account_history, through: :account
end

class Account < ApplicationRecord
  belongs_to :supplier
  has_one :account_history
end

class AccountHistory < ApplicationRecord
  belongs_to :account
end

has_and_belongs_to_many 연관성

has_and_belongs_to_many 연관은 모델을 개입시키지 않고 다른 모델과 직접적인 many-to-many 연결 many-to-many 생성합니다.

예를 들어 응용 프로그램에 assembliesparts 포함되어 있고 각 어셈블리의 파트 수가 많고 각 파트가 여러 어셈블리에 나타나는 경우 다음과 같이 모델을 선언 할 수 있습니다.

class Assembly < ApplicationRecord
  has_and_belongs_to_many :parts
end

class Part < ApplicationRecord
  has_and_belongs_to_many :assemblies
end

자기 참조 협회

자체 참조 연결은 모델을 자체와 연관시키는 데 사용됩니다. 가장 빈번한 예는 친구와 그의 추종자 간의 관계를 관리하는 것입니다.

전의.

rails g model friendship user_id:references friend_id:integer

이제 모델을 다음과 같이 연결할 수 있습니다.

class User < ActiveRecord::Base
  has_many :friendships
  has_many :friends, :through => :friendships
  has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
  has_many :inverse_friends, :through => :inverse_friendships, :source => :user
end

다른 모델은 다음과 같이 보입니다.

class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, :class_name => "User"
end


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow