2011-08-25 37 views
3

我已經搜索了幾個關於遷移及其答案的問題,但我沒有找到令人滿意的解決方案。has_many&belongs_to在postgres中使用外鍵和數據庫約束進行遷移?

我想用簡單的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 

我還是希望找到一個更好的解決方案。也許有一個寶石。

回答

4

使用優秀的foreigner寶石添加外鍵在您的遷移:

add_foreign_key :posts, :users 
add_foreign_key :comments, :users 
add_foreign_key :comments :posts 
+0

好極了!正是我需要的,謝謝! –