开发者

Get the ID of a ActiveRecord model before it is created, so you can put it in other columns (users.created_by_id == users.id)?

开发者 https://www.devze.com 2023-02-28 21:23 出处:网络
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 som

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:

  1. Leave it as null, so to find users who signed up I'd look for created_by_id IS NULL.
  2. 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.

0

精彩评论

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