是数据完整性的重要on Rails的ActiveRecord的协会使用Ruby的时候? [英] Is data integrity important when using Ruby on Rails ActiveRecord's associations?
问题描述
我只是在玩回报率和我注意到,ActiveRecord的协会,如的has_many
或 belongs_to的
是从数据库中运行的背后脱钩,即这些关联设置无论在数据库中设置的限制。例如,我有一个表评论
和表用户
键,它们通过的has_many关系
和 belongs_to的
语句(注释属于用户和用户有很多评论)。然而,这些协会还是让我分配一个注释到,例如,非现有用户。这样做的原因是,有一个在数据库中定义的任何外键。
I'm just playing with RoR and I've noticed that ActiveRecord associations such as has_many
or belongs_to
are decoupled from the database running behind, i.e., these association are set regardless of the the constraints set by the database. For example, I have a table comments
and a table users
and they are related through has_many
and belongs_to
statements (a comment belongs to a user and a user has many comments). However these associations still let me assign a comment to a, for example, non-existing user. The reason of this is that there's no foreign key defined in the database.
我的问题是:我应该仅仅依靠ActiveRecord的协会来处理数据的完整性或者我应该也是在迁移文件中添加外键?
My question is: should I just rely on ActiveRecord's associations to handle data integrity or should I also add foreign keys in migration files?
感谢你。
推荐答案
的Rails拥有一些约定执行数据的完整性应在应用程序来完成,而不是在数据库中。
Rails holds some conventions that enforcement of data integrity should be done in the application, not in the database.
要保持应用程序级数据的整数,则可以使用模型验证执行协会的presence。
To keep data integer on application-level, you can use model validations to enforce the presence of associations.
这篇关于是数据完整性的重要on Rails的ActiveRecord的协会使用Ruby的时候?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!