I have two tables.
users
superpowers
I want each user
to be limited to one superpower
. But different users
can have the same superpower
. (sam can have fire, john can have lightning, sarah can also have lightning. But every user can only have one super power)
I want to store the foreign key in the user table.
Will a has_one
and belongs_to
relationship be suitable for this?
user
has_one
superpower
.
superpower
belongs_to
user
The rails guide says has_one sets up a one to one relationship. But a subtle nuance is not addressed: whether the "belonging" model (i.e. superpowers) can belong to multiple "has_one-ing" models (i.e.
users`), where each association is a one-to-one relationship (e.g. john has lightning, and sarah also has lightning).
OR, does it mean that both the "belonging" model and the "having" model must both be unique in all associations? (e.g. if john has lighting, sarah cannot have lightning)?
Looking at your description (especially the part about foreign key being in users
table), the relationship should be:
Superpower.has_many :users
User.belongs_to :superpower
The belongs_to
part of association is always at the model with foreign key.