Rails 中的一对一或零关联 [英] one to one or zero association in rails
问题描述
模型一
class TimeLog :破坏结尾
模型二
class CustomTimeFields
以上在数据库方面的设计将是
时间日志表 + custom_time_field_id(外键)
custom_time_fields
因此,当我删除 timelog 条目时,其关联的custom_time_field"将被 rails 自动删除
但我想要如下的数据库设计
表一:
时间日志
表二
custom_time_fields(以 time_log_id 作为外键)
表 I 将与表 II 零或一个关联
如何在 Rails 模型中表示上述数据库设计,以便在删除 time_log 时,关联的 custom_time_field 条目会自动删除.
您必须切换模型的 has_one
和 belongs_to
关系,以更改包含外部的表键(具有 belongs_to
关系的模型是持有外键的模型).不要忘记根据更改调整您的迁移(声明 time_log_id
列).
我认为您正在寻找的零或一"关系是 has_one
关系.这种关系不是强制性的(除非您向其添加验证)..>
Model I
class TimeLog < ActiveRecord::Base
has_one :custom_time_fields, :dependent => :destroy
end
Model II
class CustomTimeFields < ActiveRecord::Base
belongs_to :time_log
end
above design in terms of database will be
timelogs table + custom_time_field_id(foreign key)
custom_time_fields
So when i delete timelog entry its associated 'custom_time_field' will be auto deleted by rails
But i want database design like following
Table I:
time_logs
Table II
custom_time_fields (having time_log_id as foreign key)
Table I will have Zero or one association of Table II
How can i represent above database design in Rails models, so that when i delete time_log, associated custom_time_field entry is auto deleted.
You have to switch the has_one
and belongs_to
relations of your models to change the table containing the foreign key (the model with the relation belongs_to
is the one holding the foreign key). Do not forget to adapt your migrations according to the change (to declare the time_log_id
column).
I think the "zero or one" relation you're looking for is the has_one
relation. This relation is not mandatory (unless you add a validation to it).
这篇关于Rails 中的一对一或零关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!