IT이야기

Rails의 모델에 대한 외래 키 관계 정의

cyworld 2021. 10. 22. 21:25
반응형

Rails의 모델에 대한 외래 키 관계 정의


Post 클래스에 :foreign_key가 post_id인 Comment 클래스가 있습니다.

class Comment < ActiveRecord::Base
  belongs_to :post, :class_name => "Post", :foreign_key => "post_id", :counter_cache => true
  belongs_to :author, :class_name => "User", :foreign_key => "author_id"
end

그러나 내 CreateComments 마이그레이션은 데이터베이스 수준 외래 키를 정의하지 않습니다.

class CreateComments < ActiveRecord::Migration
  def self.up
    create_table :comments do |t|
      t.column "post_id",       :integer,   :default => 0, :null => false
      t.column "author",        :string,    :default => "",   :limit => 25, :null => false
      t.column "author_email",  :string,    :default => "",   :limit => 50, :null => false
      t.column "content",       :text,      :null => false
      t.column "status",        :string,    :default => "",   :limit => 25, :null => false
      t.timestamps
    end
  end

  def self.down
    drop_table :comments
  end
end

대신 post_id는 단순한 정수 열입니다.

따라서 이러한 외래 키 관계는 데이터베이스 수준이 아닌 Rails의 마음 속에만 존재하는 것 같습니다.

이 올바른지?

또한 해당 Post 모델이 :foreign_key 속성을 사용하여 Comments와 상호 외래 키 관계를 선언해야 합니까 아니면 생략할 수 있습니까?

class Post < ActiveRecord::Base
  set_table_name("blog_posts")
  belongs_to :author, :class_name => "User", :foreign_key => 'author_id'
  has_many :comments, :class_name => "Comment",
    :foreign_key => 'post_id', :order => "created_at desc", :dependent => :destroy
  has_many :categorizations
  has_many :categories, :through => :categorizations
  named_scope :recent, :order => "created_at desc", :limit => 5

end

Rails의 기본 동작은 모델의 외래 키를 유지하는 데 사용되는 열이 접미사가 _id추가된 연결 이름이라는 것입니다 . :foreign_key옵션을 사용하면 외래 키의 이름을 직접 설정할 수 있습니다. 사용자 클래스 PostComment모델 클래스 간의 연결은 다음 같아야 합니다.

class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post
end

당신이 필요로하지 않습니다 - 주 :class_name => "Post"당신의 Comment모델. Rails는 이미 그 정보를 가지고 있습니다. 당신은 지정해야 :class_name하고 :foreign_key당신이 레일 '규칙을 무시해야 할 때.

Rails가 외래 키 관계를 유지한다는 것은 맞습니다. 외래 키 제약 조건을 추가하여 원하는 경우 데이터베이스 계층에서 적용할 수 있습니다.

ReferenceURL : https://stackoverflow.com/questions/904421/defining-foreign-key-relationships-for-rails-models

반응형