2017-02-06 3 views
0

저는 Ruby on Rails에서 새롭게 변경되었습니다. 나는 레일이 외래 키를 사용하는 방식을 이해하지 못한다. 나는 그것을 몇 일간 연구했지만 대답을 얻지 못했다.외래 키로 파괴하지 않기

간단한 예제 :

class CreatePosts < ActiveRecord::Migration 
def change 
    create_table :posts do |t| 
    t.string :title 
    t.text :content 
    t.timestamps null: false 
    end 
end 
end 


class CreateComments < ActiveRecord::Migration 
def change 
    create_table :comments do |t| 
    t.string :author 
    t.text :content 
    t.references :post, index: true, foreign_key: true 
    t.timestamps null: false 
    end 
end 
end 

내 모델은 다음과 같습니다 :

나는 두 테이블을 생성

class Post < ActiveRecord::Base 
    has_many :comments 
end 

class Comments < ActiveRecord::Base 
belongs_to :post 
end 

내 의심의 여지가있다 : 내 테이블 코멘트에서 외래 키 (가지고. reference : post, index : true, foreign_key : true) 나는 그와 관련된 COMMENTS가있는 게시물을 파기 할 수 없을 것이라고 생각하지 않습니까?

나는 위와 같이했으나 관련 의견이있는 경우에도 게시물을 삭제할 수 있습니다. 어떻게 치료할 수 있습니까? 내가 도대체 ​​뭘 잘못하고있는 겁니까?

건배

+0

을 또한 SQL LITE를 사용할 때 FK가 내 .schema를 확인하면 t가 생성 된 것처럼 보입니다. – Costa

+0

sqlite> .schema posts CREATE TABLE "posts"("ID"INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "ti tle "varchar,"content "텍스트,"created_at "datetime NOT NULL,"updated_at "datetime NOT NULL); – Costa

+0

CREATE TABLE "comments"("id"INTEGER PRIMARY KEY AUTOINCREMENT NULL이 아닌 "author"varchar, "content"텍스트, "post_id"정수, "created_at"datetime NOT NULL, "updated_at"datetime NOT NULL); CREATE INDEX "index_comments_on_post_id"ON "comments"("post_id"); – Costa

답변

0

내가 이해하는 바로는, 당신이 comments이 연결되어있는 경우 post을 파괴하려는 해달라고?

은 왜 post

의 삭제 버튼을 캡슐화 if statement을 넣지 그래서 뭔가 같은 :

psudo 코드

if @post.comments exists 
    cant delete post 
else 
    delete post 
end 
나는 :on_delete 옵션을 사용하여 마이그레이션을 수정할 것
0

외래 키에. 그것은 그 값 중 하나를 취할 수 있습니다 :nullify, :cascade, :restrict

내가 이해에서 관련 의견 게시물이 삭제 될 수 있도록, 당신이 당신의 comments 테이블에 post_id:restrict이 값을 설정해야합니다.

has_many :comment, dependent: :restrict_With_error 

가 살펴 보시기 바랍니다 : 당신은 또한 직접 Post 모델 협회에 설정할 수 또는 :

업데이트

http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_foreign_key http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many을 -> 옵션 참조 : 제