【问题标题】:has_many & belongs_to migration with foreign keys and database constraints in postgres?has_many & belongs_to 在 postgres 中使用外键和数据库约束进行迁移?
【发布时间】:2011-08-25 21:30:45
【问题描述】:

我搜索了几个关于迁移的问题及其答案,但没有找到满意的解决方案。

我想使用简单的 has_many 和 belongs_to 关系,比如

class User < ActiveRecord::Base
  has_many :posts
  has_many :comments
end

class Post < ActiveRecord::Base
  belongs_to :user
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post
  belongs_to :user
end

是否有可能在迁移中创建数据库级别的约束,例如

post_id integer REFERENCES posts

还是我必须手动执行此操作?充其量我更喜欢独立于数据库的解决方案。提前致谢!

编辑:我目前正在使用 Postgresql,但我喜欢在底层数据库方面灵活一些。

更新:为了独立于数据库的代码,我目前坚持以下迁移:

class AddRelations < ActiveRecord::Migration
  def self.up
    add_column :posts, :user_id, :integer, :null => false
    add_column :comments, :user_id, :integer, :null => false
    add_column :comments, :post_id, :integer, :null => false
  end

  def self.down
    remove_column :posts, :user_id
    remove_column :comments, :user_id
    remove_column :comments, :post_id
  end
end

我还是希望能找到更优雅的解决方案。也许有一个宝石。

【问题讨论】:

    标签: ruby-on-rails-3 rails-migrations rails-postgresql


    【解决方案1】:

    使用出色的 foreigner gem 在迁移中添加外键:

    add_foreign_key :posts, :users
    add_foreign_key :comments, :users
    add_foreign_key :comments :posts
    

    【讨论】:

      猜你喜欢
      • 2018-01-23
      • 2020-10-30
      • 1970-01-01
      • 2019-02-20
      • 1970-01-01
      • 2021-12-05
      • 2020-08-14
      • 1970-01-01
      • 2013-09-10
      相关资源
      最近更新 更多