'Rails Associations - has_one, belongs_to_many
It's been a while since I've worked with Rails (Rails 6) on a new application. I'm failing to recall how to properly set up associations. I have two problems that are rather similar and may help to answer each other. I understand that the model containing belongs_to will hold the foreign key, however, it feels backward in my head.
- I have a User model with a
pronounsattribute. I have a Model/Tablepronouns. A user can have one pronouns record associated with is (has_one?). But a pronouns record can belong to any number of users. Sobelongs_towon't work in this case, since the foreign key would be on thepronounstable. The way that I've sort of gotten around this is to usebelongs_to, but this doesn't feel right because I need to make it optional sincepronounsisn't required for a user.
class User < ApplicationRecord
belongs_to :pronouns, optional: true
end
class Pronoun < ApplicationRecord; end
- I have the following models: Location, User, Experience, JobPost. In this case, User, Experience, and JobPost can have a single location, but Location can belong_to (have_many?) of each of these. This feels like a case for a polymorphic association. Where I'm feeling confused is what the
has_onemodel (user, experience, job post) looks like. Do they have one? They shouldn't have many.
This is a work in progress, so there isn't much more code-wise I can really add. But if there are any areas where I can share more or elaborate, I'm happy to.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
