2016-07-28 2 views
0

내가 외래 키 레일을 추가하는 방법은 무엇입니까?

class User 
    has_many :questions, trough: votes 
    has_many :questions  #(as the author) 
    has_many :votes 
end 

을 만들 때 foreign_key을 추가 잊으해야합니까 더 간단하게하기 위해, 지금은 특정 (has_many를 통해) 연결

schema.rb

에 추가하는 방법을 모른다
enable_extension "plpgsql" 

    create_table "answers", force: :cascade do |t| 
    t.text  "body" 
    t.datetime "created_at",     null: false 
    t.datetime "updated_at",     null: false 
    t.integer "question_id" 
    t.integer "user_id" 
    t.boolean "best",  default: false 
    end 

    add_index "answers", ["question_id"], name: "index_answers_on_question_id", using: :btree 
    add_index "answers", ["user_id"], name: "index_answers_on_user_id", using: :btree 

    create_table "attachments", force: :cascade do |t| 
    t.string "file" 
    t.datetime "created_at",  null: false 
    t.datetime "updated_at",  null: false 
    t.integer "attachable_id" 
    t.string "attachable_type" 
    end 

    add_index "attachments", ["attachable_id", "attachable_type"], name: "index_attachments_on_attachable_id_and_attachable_type", using: :btree 

    create_table "questions", force: :cascade do |t| 
    t.string "title" 
    t.text  "body" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    t.integer "user_id" 
    end 

    add_index "questions", ["title"], name: "index_questions_on_title", using: :btree 
    add_index "questions", ["user_id"], name: "index_questions_on_user_id", using: :btree 

    create_table "users", force: :cascade do |t| 
    t.string "name" 
    t.datetime "created_at",       null: false 
    t.datetime "updated_at",       null: false 
    t.string "email",     default: "", null: false 
    t.string "encrypted_password",  default: "", null: false 
    t.string "reset_password_token" 
    t.datetime "reset_password_sent_at" 
    t.datetime "remember_created_at" 
    t.integer "sign_in_count",   default: 0, null: false 
    t.datetime "current_sign_in_at" 
    t.datetime "last_sign_in_at" 
    t.inet  "current_sign_in_ip" 
    t.inet  "last_sign_in_ip" 
    end 

    add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree 
    add_index "users", ["name"], name: "index_users_on_name", unique: true, using: :btree 
    add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree 

    create_table "votes", force: :cascade do |t| 
    t.integer "votable_id" 
    t.string "votable_type" 
    t.integer "user_id" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    end 

    add_index "votes", ["user_id", "votable_id"], name: "index_votes_on_user_id_and_votable_id", unique: true, using: :btree 

    add_foreign_key "answers", "questions", on_delete: :cascade 
    add_foreign_key "questions", "users", on_delete: :cascade 
end 
+0

당신이 당신의'dB/schema.rb'를 게시 할 수 있습니까? – siegy22

+0

다른 모델의 user_id를 의미합니다. –

+0

RaVeN 'code'create_table "votes", force : : cascade do | t | t.integer "votable_id" t.string "votable_type" t.integer "user_id" t.datetime "created_at", null : false t.datetime "updated_at", null : false end –

답변

0

실행 콘솔에서이 명령

rails g migration AddForeignKeyToVotes user:references question:references 

이 다음과 같은 내용

class AddForeignKeyToVotes < ActiveRecord::Migration 
    def change 
    add_reference :votes, :user, index: true, foreign_key: true 
    add_reference :votes, :question, index: true, foreign_key: true 
    end 
end 
+0

문제는 외래 키가 필요합니다. Im 초심자이고, 나는 someth 이해할지도 모른다. 그러나이 추가의 목적은 has_many : questions가 있어야하는 별명을 만드는 것입니다. 이름이 지정된 외래 키를 추가하여 별개로 추가하고자합니다. –

0

db/migrate/ 아래 xxxx_add_foreign_key_to_votes.rb 파일을 생성합니다 당신이 정말로 외래 키를 필요가 있습니까?

많은 Rails 개발자는 Rails가 데이터베이스가 아닌 응용 프로그램에서 관계를 처리하는 방식에 만족합니다. 귀하의 경우에 대한

:

class User 
    has_many :questions, trough: votes 
    has_many :questions  #(as the author) 
    has_many :votes 

경우 votes 테이블이 question_id 그리고 당신은 이유가없는 한, 모든 외래 키없이 관계를 정의하기에 충분하고 정말이 외래 키가 필요 user_id 데이터베이스 수준을 정의해야합니다.

THIS SECTION을 자세히 읽고, 레일즈는 Convention over Configuration을 사용하고 있습니다.

작은 예제로 : 어떤 테이블을 쿼리하고 데이터를 검색 할지를 모델이 알지 못한다면, 같은 이름을 가진 테이블을 검색하여 외래 키와 동일한 이름으로 users (관행)을 사용하십시오.

class User 
    has_many :asked_questions, class_name: 'Question' # user can ask many questions 
    has_many :voted_questions, through: :votes, source: 'question' 
    has_many :votes # to get all votes this user did 
end 

class Question 
    has_many :votes # to get all votes for a question 
    belongs_to :user 
end 

class Vote 
    belongs_to :user 
    belongs_to :question 
end 

데이터베이스 뭔가 될 것입니다 : 당신이 유래와 같은 모델 뭔가를 귀하의 코멘트에 따르면

, 당신은 User는 누가 Question을 요청할 수 있습니다 당신이 뭔가를 할 수 있습니다이 경우에는 Question 대답 할 수 있습니다 같은 :

# Table User 
# Table Question (user_id) 
# Table Vote (user_id, question_id) 

의 당신이 Questions 사용자가 될 것 그들이 물었다 싶어한다고 가정 해 봅시다 :

user = User.first 
user.asked_questions 

당신이 Questions 사용자의 표를 얻을하려는 경우 :

user.voted_questions 
+0

mohamed-ibrahim 분리를 처리하기 위해 필요합니다. 나는 틀린 길을 가고 있을지도 모르지만 유권자로서의 저자와 질문으로 질문을하고 싶습니다/이것들은 다른 협회입니다 –

+0

@ anti-k는 내 업데이트 된 답변을 확인합니다 –

+0

mohamed-ibrahim 고마워요! –

관련 문제