Reputation: 1752
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.
Upvotes: 2
Views: 2808
Reputation: 24350
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).
Upvotes: 5