문제

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.

도움이 되었습니까?

해결책

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top