【问题标题】:Rails 4.2.7 mysql set two custom primary keyRails 4.2.7 mysql设置两个自定义主键
【发布时间】:2016-11-20 01:14:15
【问题描述】:

我有两个表名为 Post 和 Like。我想在 Like 表中设置“ip”和“reference to post”作为我的两个主键。我可以从帖子表中成功创建具有两个唯一键“ip”和“id”的喜欢表。但是当我尝试从我的 rails 控制台创建示例数据时,它会首先检查是否存在相同的“ip”。如果相同的“ip”已经存在,即使帖子完全不同,它也不会创建数据。

这是我目前所拥有的。

喜欢表

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

【问题讨论】:

  • 请注意t.references :post 添加了一个名为post_id 的整型列,而不是post。

标签: mysql ruby-on-rails activerecord


【解决方案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

【讨论】:

  • 感谢您建议使用组合键。
猜你喜欢
  • 2013-10-03
  • 1970-01-01
  • 1970-01-01
  • 2013-02-15
  • 2018-06-09
  • 2011-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多