2016-08-29 2 views
0

내가 내 Heroku가 서버에 내 레일 프로젝트에 대한 내 MySQL 데이터베이스를 시드 시도하고 나는이 오류가 무엇입니까 실패 놀랍게도레일 + Heroku가 : 외래 키 제약 조건이

ActiveRecord::InvalidForeignKey: Mysql2::Error: Cannot add or update a child row: a foreign key constraint fails (heroku_b08bb4ad8dfb726 . posts , CONSTRAINT fk_rails_5b5ddfd518 FOREIGN KEY (user_id) REFERENCES users (id)): INSERT INTO posts (id , title , description , user_id , category_id , created_at , updated_at) VALUES (1, 'Title', 'Desc', 1, 1, '2016-08-29 06:53:04', '2016-08-29 06:53:04')

을,이 오류가 발생하지 않습니다 내 개발 환경에서.

시드 파일의 추출물은 다음과 같습니다

# Creating Users here 

Category.create!([ 
    { id: 1, name: "Category"}, 
]) 

Post.create!([ 
{ id: 1, title: "Title", description: "Desc", user_id: "1", category_id: "1" }, 
]) 

포스트 모델 :

class Post < ApplicationRecord 
    belongs_to :user 
    belongs_to :category 
    has_many :comments 
    validates :title, :description, presence: true 
end 

카테고리 모델 :

class Category < ApplicationRecord 
    has_many :posts 
end 

댓글에 코드 스 니펫이 더 필요하면 알려주십시오. 이 문제에 대한 아이디어를 주셔서 대단히 감사합니다. 당신이 당신의 시드 파일이 추가 id = 1

으로 데이터베이스에 user이 없기 때문에

답변

1

는 또한

제약이 실패하여 seed.rb에서 사용자를 생성해야

user = User.create(
    # user attributes like `name` 
) 

Post.create!([ 
{ id: 1, title: "Title", description: "Desc", user_id: user.id, category_id: "1" }, 
]) 

user_id과 같은 값을 하드 코딩하는 대신 first 또는 last을 사용해야합니다. 또는 임의의 레코드로 제한 실패를 피하십시오.

+0

답장을 보내 주셔서 감사합니다. 죄송합니다. 이미 시드 파일에 사용자를 생성하고 있습니다. 내 질문을 편집했습니다. – patrick

+0

그런 다음 사용자를 전달하는 'user_id'가 존재하는지 확인하십시오. –

+0

이제이 문제에 직면하고 있습니다 : http://stackoverflow.com/questions/39200815/mysql-rails-errno-150-foreign-key-constraint- 잘못 만들어진 – patrick