开发者

has_many & belongs_to migration with foreign keys and database constraints in postgres?

开发者 https://www.devze.com 2023-03-31 01:00 出处:网络
I\'ve searched several questions about migrations and their answers, but I didn\'t find a satisfactory solution.

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 o开发者_运维技巧f 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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消