I’m working on a Rails app that will contain information on a bunch of people. There are two use cases:
- An administrator enters and maintains a person’s profile
- The person can decide to sign up, log in, and maintain their own profile
I’m trying to work out the relationship between the profile and the user. Right now, it’s that profile belongs_to :user, and user has_one :profile.
But this breaks, because some profiles have no user yet – they are administrator-maintained. In that case, the user_id column in profiles is null, the join fails, and the page won’t load.++
How might I set up a “possibly belongs_to” kind of relationship?
++(Actually, it comes up blank, with no error displayed, and development.log doesn’t have any errors either, but I can see that it’s not finishing all the queries it does for a profile that does have a user. If anybody knows how I can get a helpful error message instead, that would also be great.)
This is the right way to do it.
belongs_todoesn’t preventnullvalues, and this sounds like what you want.The “page” for a profile that doesn’t yet belong to a user might not have as many queries, because there’s no need (or way) to query the users table for that profile.
You should check
profile.userforniland present your views accordingly.