Should I use has_one or belongs in ruby ​​on rails?

I want to have a Status model that will be relatively static after a certain user setting (and different users may have different status values).

Status can apply to various models, such as Contact and Event .

therefore, the statuses returned by contact.status will be different from event.status

I want to create an application so that the 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 saving :status_id in the table :contacts . Also with Event .

:statuses table will have a status value, type and date.

it makes sense? Can you suggest a better approach?

+7
ruby-on-rails belongs-to
source share
3 answers

There is guidance on this . Your situation is somewhat different in that it seems that your state model really needs to be polymorphic, because different things will be β€œstatus”.

To answer your question, Contact / Event has_one Status makes sense to me.

+7
source share

Just to complete the answer in a more general setting that can choose your choice: belongs_to association is used in the model with a foreign key.

+2
source share

First, the has_one relationship does not store the identifier in the current model. He is looking for a foreign key in a comparison table. To save status_id in contacts or events, you must use belongs_to.

Secondly, depending on the type of information that you keep in status, why should it be a separate separate table? Why not create a status column in each model on which you want to use the status? A little more information may be helpful here.

+1
source share

All Articles