Home > Enterprise >  Find ID of User to add to another field
Find ID of User to add to another field

Time:01-06

I am attempting to retrieve the ID of the user from the User table in order to pass the id to the metadata field of the File table. Within the model of the file table I added the relation belongs to :user. When the User uploads a file a record is created in the File table. As a result of this I have also added after_create :update_metadata' to update the metadata field.

Within the 'update_metadata' method I need to find a way to grab the user ID and pass it into the metadata field when a File is uploaded. I assumed user_id = User.find(id) update_attribute(:metadata, user_id) would work but nothing is displayed in the metadata field.

I expected the field to be updated with the User's ID.

CodePudding user response:

If you have added the association in file model as:

belongs_to :user

There must be a user_id present in file object in the database determining which user it belongs to.

So you can access that by file_object.user_id or file_object.user.id

Note: In the after_create callback you can access your file object directly or by using self keyword

  • Related