Rails update associated model's object

时间:2016-04-07 10:42:52

标签: ruby-on-rails ruby-on-rails-4.2

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?

1 个答案:

答案 0 :(得分:0)

使用此行,您可以创建新用户(如果该用户不存在)并更新其数据。

opportunity.user.find_or_create_by(email: user_params[:email]).update(user_params)

如果用户已更新,此方法将返回true / false。如果您希望用户自己创建,请使用:

opportunity.user.find_or_create_by(email: user_params[:email]).tap{ |user| user.update(user_params) }

编辑: 这有用:

opportunity.user = User.find_or_create_by(email: user_params[:email]).tap{ |user| user.update(user_params) }