1

I need an api key to save a user, and I need a user_id to save an api_key... Can I do both at once?

user.api_key = ApkiKey.generate_token
user.save
user.api_key.user_id = user.id
user.api_key.save

2 Answers 2

2

If the api_key has belongs_to relationship with user then following will work

user.api_key = ApkiKey.generate_token
user.api_key.user_id = user.id
user.save

the user.save will also trigger the user.api_key.save

Sign up to request clarification or add additional context in comments.

Comments

1

I ended up doing the following:

#api_key.rb
before_create :generate_access_token
def generate_access_token
    begin
        self.access_token = SecureRandom.hex
    end while self.class.exists?(access_token: access_token)
end

#user.rb
before_create do |user|
    user.api_key = ApiKey.create(user_id: user.id)
end

The problem was that I didn't think I could access user.id before I created the user, but apparently it works. Thanks for the heads up @Hardik

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.