1

I have two tables User (Devise) and Phones

I would like for it when the user signs up threw registrations done with devise, the user_id and the type of phone is loaded into the Phones table

But I am not sure how to do this. I have linked the User with Phones with

User.rb

has_many :phones

Phones.rb

belongs_to :user

db (schema)

 t.index ["user_id"], name: "index_phones_on_user_id"

Any help would be appreciated

1

2 Answers 2

4

you can run an after_create callback on User model

after_create :assign_phone

private

def assign_phone
  phone = phones.new
  # assign required values
  phone.save
end

As mentioned in the comments, phone.save will silently return false if there's an error, using !(bang) will raise and error another solution is checking if it is saved or not and then perform task that you want..

def assign_phone
  phone = phones.new
  # assign required values
  if phone.save
    #on successfull save
  else
    #on failure
  end
end
Sign up to request clarification or add additional context in comments.

4 Comments

phone.save silently ignores any error that could happen with phones, that is an awful advice. One should at least use phone.save! there.
I think assign_phone should use self.build_phones as relationship is not developing between user and phone?
@mudasobwa I agree, but since I wanted to provide basic structure, I ignored that, thanks though, I will update.
@SulmanBaig the relationship is being created, self is implied and redundant so no need to use it there, as I am in the model itself with the user's instance. i.e. self.phones.new == phones.new
0

in user.rb

after_create :assign_phone

def assign_phone
  phone = self.phones.build
  phone.save
end

This way you will not be able to add type of phone. However, if you want to save type as well then you have to override "create" method of devise/registrations_controller.rb

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.