I have 2 tables: contacts and users (Devise).
I would like to create a user each time an contact is created.
The contact belongs_to :user
The user has_one :contact
The following code in the contact.rb file creates the user when you add a new contact:
before_create :create_user
protected
def create_user
self.user = User.new({ :email => self.email, :password => '123456' })
return user.save
end
But, the contact field user_id (foreign key) isn’t getting updated with the new user id.
How can accomplish that?
Thanks!
Try this instead
My guess is that the association is not being registered because after the
User.newcall the object has not been saved to the database and has not been assigned an id attribute, and the id attribute is what is required to record the association.User.createinitializes the object and saves it to the database in one step (assuming all validations pass).