Question

I'm working on a Rails app that will contain information on a bunch of people. There are two use cases:

  1. An administrator enters and maintains a person's profile
  2. 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.)

Was it helpful?

Solution

This is the right way to do it. belongs_to doesn't prevent null values, 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.user for nil and present your views accordingly.

OTHER TIPS

If a Profile really belongs to a User, then it shouldn't ever be null (just like it doesn't make sense to consider an Engine without the Car it's attached to). So you need to delete the Profile.belongs_to :user association.

Now you should be able to freely edit Profiles and simply attach them to a User once they're ready. But you have another problem:

The person can decide to sign up, log in, and maintain their own profile

How does the system reliably identify which pre-created profile belongs to a particular user that doesn't yet have a profile? That's a design issue you'll have to sort out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top