Johji
Johji

Reputation: 250

Rails 4.2.7 mysql set two custom primary key

I have two tables called Post and Like. I want to set "ip" and "reference to post" as my two primary key in Like table. I can successfully create the likes table with two unique key 'ip' and 'id' from posts table. But when I try to create sample data from my rails console it will first check if the same 'ip' exist. If the same 'ip' is already existing it will not create the data even if the post is completely a different one.

This is what I have so far.

Likes Table

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 

end

Posts Table

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

Upvotes: 0

Views: 300

Answers (1)

Arslan Ali
Arslan Ali

Reputation: 17802

Having two primary key in a single table doesn't make sense. If you really have two keys that will always uniquely identify data, you can have a combined key of those two keys, and that combined key will act as a primary key.

Here's is how you can accomplish this in 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

And in your Like model:

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

Upvotes: 1

Related Questions