【发布时间】:2011-08-25 21:30:45
【问题描述】:
我搜索了几个关于迁移的问题及其答案,但没有找到满意的解决方案。
我想使用简单的 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
我还是希望能找到更优雅的解决方案。也许有一个宝石。
【问题讨论】:
标签: ruby-on-rails-3 rails-migrations rails-postgresql