2016-11-20 22 views
0

我有兩個名爲Post and Like的表。我想在Like表中將「ip」和「reference to post」設置爲我的兩個主鍵。我可以使用posts表中的兩個唯一鍵「ip」和「id」成功創建喜歡錶。但是當我嘗試從我的導軌控制檯創建示例數據時,它將首先檢查是否存在相同的'ip'。如果相同的'ip'已經存在,即使帖子完全不同,它也不會創建數據。Rails 4.2.7 mysql設置兩個自定義主鍵

這是我到目前爲止。

喜歡錶

class CreateLikes < ActiveRecord::Migration def change 
create_table :likes, :id => false do |t| 
    t.string :ip, limit: 39 
    t.references :post, index: true, foreign_key: true 

    t.timestamps null: false 
end 
add_index :likes, ["ip"], :unique => true 
add_index :posts, ["id"], :unique => true 
end 

帖子表

class CreatePosts < ActiveRecord::Migration def change 
create_table :posts do |t| 
    t.string :title 
    t.string :body 
    t.string :media 

    t.timestamps null: false 
end 
end 
end 
+0

請注意,'t.references:POST'添加一個名爲整數類型的列'post_id',而不是命名的'post'。 –

回答

1

在一間單獨的表中的兩個主鍵是沒有意義的。如果您確實有兩個密鑰總是唯一標識數據,那麼您可以使用這兩個密鑰的組合密鑰,而組合密鑰將充當主密鑰。

這裏的是如何在Rails的做到這一點:

class CreateLikes < ActiveRecord::Migration 
    create_table :likes, id: false do |t| 
    t.string :ip, limit: 39 
    t.references :post, index: true, foreign_key: true 

    t.timestamps null: false 
    end 
    execute "ALTER TABLE likes ADD PRIMARY KEY (ip,post_id);" 
end 

而在你Like型號:

class Like < ActiveRecord::Base 
    self.primary_keys = :ip, :post_id 
end 
+0

謝謝你建議使用組合鍵。 – Johji