“참조”마이그레이션에서 열 이름 지정
migration
다른 테이블을 참조하여 Rails 를 만들고 싶습니다 . 일반적으로 다음과 같은 작업을 수행합니다.
add_column :post, :user, :references
이것은라는 이름의 열 생성 user_id
에 posts
테이블을. 그러나 대신에 user_id
내가 원하는 것을 원한다면 author_id
어떻게해야합니까? 어떻게해야합니까?
수동으로 수행하십시오.
add_column :post, :author_id, :integer
하지만 이제 belongs_to 문을 만들 때는 수정해야하므로 이제 전화해야합니다
def post
belongs_to :user, :foreign_key => 'author_id'
end
에서 레일 4.2 당신은 또한 설정할 수 있습니다 외부 키 뿐만 아니라 DB에 좋은 생각이다 .
간단한 연결의 t.references
경우을 추가 foreign_key: true
해도 가능하지만이 경우 두 줄이 필요합니다.
# The migration
add_reference :posts, :author, index: true
add_foreign_key :posts, :users, column: :author_id
# The model
belongs_to :author, class_name: "User"
레일 5 이상
초기 정의 :
당신이 정의하는 경우 Post
모델 테이블을, 당신은 설정할 수 있습니다 references
, index
그리고 foreign_key
한 줄에 :
t.references :author, index: true, foreign_key: { to_table: :users }
기존 업데이트 :
기존 테이블에 대한 참조를 추가하는 경우 다음을 수행 할 수 있습니다.
add_reference :posts, :author, foreign_key: { to_table: :users }
참고 : 의 기본값 index
은 true입니다.
rails 4에서는 postgresql과 schema_plus gem을 사용할 때 쓸 수 있습니다.
add_reference :posts, :author, references: :users
이것은 author_id
올바르게 참조 하는 열을 생성합니다 users(id)
.
그리고 당신의 모델에서는
belongs_to :author, class_name: "User"
새 테이블을 만들 때 다음과 같이 작성할 수 있습니다.
create_table :things do |t|
t.belongs_to :author, references: :users
end
참고 :
schema_plus
전체에 있는 gem은 rails 5+와 호환되지 않지만이 기능은 rails 5와 호환되는 gem schema_auto_foreign_keys (schema_plus의 일부)에 의해 제공됩니다 .
외래 키를 사용하지 않는 경우 다른 테이블의 실제 테이블 이름이 중요하지 않습니다.
add_reference :posts, :author
Rails 5 부터 외래 키를 사용하는 경우 외래 키 옵션에서 다른 테이블의 이름을 지정할 수 있습니다. ( 토론 https://github.com/rails/rails/issues/21563 참조 )
add_reference :posts, :author, foreign_key: {to_table: :users}
Rails 5 이전에는 외래 키를 별도의 단계로 추가해야합니다.
add_foreign_key :posts, :users, column: :author_id
alias_attribute (new_name, old_name) 는 매우 편리합니다. 모델과 관계를 작성하십시오.
rails g model Post title user:references
그런 다음 모델을 편집하고 속성 별칭을 추가하십시오.
alias_attribute :author, :user
그 후에는 다음과 같은 것을 실행할 수 있습니다.
Post.new(title: 'My beautiful story', author: User.first)
참고 URL : https://stackoverflow.com/questions/13694654/specifying-column-name-in-a-references-migration
'Programing' 카테고리의 다른 글
라이센스 계약에 동의 할 수 없음 Android SDK Platform 24 (0) | 2020.07.26 |
---|---|
rails + MySQL on OSX : 라이브러리가로드되지 않았습니다 : libmysqlclient.18.dylib (0) | 2020.07.26 |
document ()와 함께 copy-of를 사용하여 XHTML 출력에 SVG 추가 (0) | 2020.07.26 |
실패 후 Internet Explorer가 Ajax 호출에서 HTTP 포스트 본문을 보내지 않는 이유는 무엇입니까? (0) | 2020.07.26 |
Java, Classpath, Classloading => 동일한 jar / 프로젝트의 여러 버전 (0) | 2020.07.26 |