开发者

Rails - how to code 'may belong to?'

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 w开发者_运维知识库on'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_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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜