Rails: belongs_to vs has_one
-
23-08-2019 - |
Question
A bit of a newbie question on rails associations.
I have a Bug model, and a Status model. Status is basically just a key/value pair table. Out of the choices available, I would say Bug has_one Status makes the most sense. However, according to this
Content belongs_to ContentTemplate. Go back and look at how I described the problem, and you'll see that it works. With belongs_to, the table accepts responsibility for the foreign key. So Content has a content_template_id. And ContentTemplate doesn't need anything. I can point to it at will. Done.
Bug belongs_to Status would be more appropriate (since Bug should take the foreign key). Semantically, his example makes sense, but mine makes none. Is this just a quirk of rails where in this situation it looks odd, or am I not understanding something/doing it wrong?
Solution
Yes, I think you've just found a slightly odd-looking scenario in Rails. I suppose it might be useful to view "status" as a sort of category to which the bug belongs — in that light, it makes sense.
OTHER TIPS
TABLE:
Bug
id integer
desc string
status_id integer fk
Status
id integer
desc string
RAILS MODEL:
Bug
belongs_to :status
Status
has_many :bugs
You didn't explain precisely what kind of relationship between Bug and Status you would like to get, but I assume you are interested in one of the following:
- one-to-many: in this case there should be
has_many
in Bug class andbelongs_to
in Status class, - one-to-one: in this case there should be
has_one
in Bug class andbelongs_to
in Status class.
In both cases Status contains the foreign key. In the second case the wording is a little odd, due to the fact that one-to-one relationship is in fact asymmetric (there should be a FK on one side only).
If Status is just a look-up/key-value table, it sounds like you might want a habtm(has_and_belongs_to_many
) relationship between Status and Bug. With habtm, what you'll end up with is a bugs_statuses
join table that has bug_id
and status_id
columns along with your bugs and statuses tables.