有_许多&属于_to迁移与postgres中的外键和数据库约束?

发布于 2024-12-01 14:37:54 字数 1179 浏览 3 评论 0原文

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

我想使用简单的 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

我仍然希望找到一个更优雅的解决方案。也许有一块宝石可以做到这一点。

I've searched several questions about migrations and their answers, but I didn't find a satisfactory solution.

I want to use simple has_many and belongs_to relationships like

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

Is there any possibility to create database level constraints inside of the migration such as

post_id integer REFERENCES posts

or will I have to do this manually? At best I'd prefer a database-independent solution. Thanks in advance!

Edit: I'm currently using Postgresql, but I like to be flexible in regards of the underlying database.

Update: For the sake of database-independent code I stick with the following migration at the moment:

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

I still hope to find a more elegant solution. Maybe there's a gem for that.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

仙气飘飘 2024-12-08 14:37:55

使用优秀的 foreigner gem 在迁移中添加外键:

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

Use the excellent foreigner gem to add the foreign keys in your migration:

add_foreign_key :posts, :users
add_foreign_key :comments, :users
add_foreign_key :comments :posts
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文