有_许多&属于_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
我仍然希望找到一个更优雅的解决方案。也许有一块宝石可以做到这一点。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用优秀的 foreigner gem 在迁移中添加外键:
Use the excellent foreigner gem to add the foreign keys in your migration: