I'm wondering if there's a better way to a开发者_如何转开发ccomplish this...
I want to set a field in the users
table, users.created_by_id
to the id of the user who created this new user. Either someone creates themselves (signup), or an admin creates them. If an admin creates them, I can use their id
. But if a user creates themselves, my only two options are:
- Leave it as
null
, so to find users who signed up I'd look forcreated_by_id IS NULL
. - Save it again after it's created, using it's ID.
Both of them aren't ideal, I'm wondering is there a recommended approach? I'm doing this in Rails.
There is nothing wrong with leaving the field null. It really depends on how you would show that information. If your intention is not to query all the users created by some other user and its just for display you can just override the accessor for created_by to return either self or the user specified by the id in the column.
You could use the after_create callback (see this rails guide if needed) to store an id. For the logic, you could say something like, if created_by_id is null, then put in my id.
I hope this helps.
精彩评论