one to one or zero association in rails

女生的网名这么多〃 提交于 2019-12-23 23:35:44

问题


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.


回答1:


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).



来源:https://stackoverflow.com/questions/10562658/one-to-one-or-zero-association-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!