My Opportunity model looks like this:
class Opportunity < ApplicationRecord
# opportunity belongs to a user
belongs_to :user
def self.create_opportunity(params)
# Fetch opportunity params and user params from request parameters
opportunity_params = params[:opportunity_params]
user_params = params[:user_params]
opportunity = Opportunity.find_or_initialize_by(id: opportunity_params[:id])
opportunity.assign_attributes(opportunity_params)
opportunity.user = User.find_or_initialize_by(email: user_params[:email])
opportunity.user.assign_attributes(user_params)
opportunity.save
end
user.rb model
class User < ApplicationRecord
# validate user email
validates :email, presence: true, email: true
enum gender: { male:1, female:2 }
end
We create a new user if a user with the email provided does not exists. This works well when a new user is created, but doesn't work when there already is a user. The update for user model doesn't work. For update on user to work, I need to specifically call opportunity.user.save
Any idea how to make this work without explicitly calling save on user model?
With this line you can create a new user if it does not exist and update its data.
opportunity.user.find_or_create_by(email: user_params[:email]).update(user_params)
This method will return true/false if the user has been updated or not. If you want the user created itself use this:
opportunity.user.find_or_create_by(email: user_params[:email]).tap{ |user| user.update(user_params) }
edit: THIS HAS TO WORK:
opportunity.user = User.find_or_create_by(email: user_params[:email]).tap{ |user| user.update(user_params) }
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.