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
def create_user
self.user = User.create({ :email => self.email, :password => '123456' })
end
My guess is that the association is not being registered because after the User.new
call 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.create
initializes the object and saves it to the database in one step (assuming all validations pass).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.