I want to have a Status
model which will be relatively static after some user-defined set up (and different users may have different values on status).
The status can apply to different models, such as Contact
and Event
.
so the statuses returned by contact.status
will be different from event.status
I want to design the app so that status table has different types (contacts
and events
).
What is the right strategy and format for this?
I am thinking of declaring :has_one Status
in the Contact
model,
and storing a :status_id
in the :contacts
table. Ditto with Event
.
:statuses
table will have the status value, type, and date.
does this make sense? Can you suggest a better approach?
They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.
belongs_to means that the foreign key is in the table for this class. So belongs_to can ONLY go in the class that holds the foreign key. has_one means that there is a foreign key in another table that references this class.
A has_one association indicates that one other model has a reference to this model. That model can be fetched through this association. For example, if each supplier in your application has only one account, you'd declare the supplier model like this: class Supplier < ApplicationRecord has_one :account end Copy.
There is a guide on this very question. Your situation is slightly different in that it seems as though your Status model really needs to be polymorphic since different things will be 'statusable'.
To answer your question, Contact/Event has_one Status does make sense to me.
Just to complete the answer in a more general setting, that can drive your choice : belongs_to
association is used in the model that has the foreign key.
Firstly, the has_one relationship does not store an id in the current model. It looks for a foreign key in the relative table. In order to store a status_id in Contacts or Events you'd use belongs_to.
Secondly, depending on the type of information you're storing in Status, why does it need to be its own separate table? Why not make a status column in each model you want to use status on? A little more information may be useful here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With