Rails - use serialized attributes or a belongs_to

2019-06-14 11:51发布

In my app I have the following models: Job and Worker. When a job is created, it is assigned a location attribute (Job#location) based on the address of the job.

When workers fill out the site's application form, they should be able to indicate what locations they are interested in working in. Somehow I will be comparing a Worker's chosen locations with the location of a Job and sending notifications to Workers who have indicated that location, etc.

In the form view, the possible locations will be presented to the applicant as checkboxes. My question is how I should approach storing this info in the database, since a Worker might be interested in working in more than one location. As far as I can tell, it is possible to serialize an attribute so that it is an array. So should I have one attribute on Worker (e.g. Worker#location_preferences) that is serialized, or should I create a new model (LocationPreference) that will be associated with Worker such that a Worker has_many LocationPreferences and a LocationPreference belongs_to a Worker? This would presumably require using nested forms in the form view.

Is one of the above a better Rails practice?

2条回答
冷血范
2楼-- · 2019-06-14 12:35

I think you answered your own question when you wrote this:

Somehow I will be comparing a Worker's chosen locations with the location of a Job and sending notifications to Workers who have indicated that location

The second you decide you need to "compare" (ie. query) serialization is going bite you in the A$$. Go with an association.

查看更多
Lonely孤独者°
3楼-- · 2019-06-14 12:46

I would recommend using a one-to-many database relationship and store the location in a Location model / locations table.

I think this because I would anticipate Location shortly having additional attributes, e.g. lat-long, description, zipcode, country, when created, when updated, etc.

The potential for all these additional attributes make choose rails model / db mode.

An example of an attribute that might be more suited to a serializable field is one that reflects a simple list of values, for example if you were storing the locations currently available public transport from a set of 4 things - walking, driving, cycling and flying, this might be more appropriate for a serialized list. I say 'might' as almost any attribute can be seen to have sub-attributes, e.g. number of wheels, time to get there by method, etc, etc.

So at the end of the day this really is a

~ It depends ~

sort of question-answer as it will depend on what data and for what purpose it is used for. In the example you give you do not give enough detailed information about what the location is used for and what it represents

查看更多
登录 后发表回答