我搜索了几个关于迁移的问题及其答案,但没有找到令人满意的解决方案。
我想使用简单的 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
我仍然希望找到一个更优雅的解决方案。也许有一个宝石。