Rails 中的一对一或零关联

编程入门 行业动态 更新时间:2024-10-24 19:14:07
本文介绍了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 中的一对一或零关联

本文发布于:2023-11-14 13:53:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587397.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!