first_or_create by email and then save the nested model

[亡魂溺海] 提交于 2019-12-03 13:08:47

first_or_create accepts a block. So you could do it as follows:

@user = User.where(:email => params[:user][:email]).first_or_create do |user|
  # This block is called with a new user object with only :email set
  # Customize this object to your will
  user.attributes = params[:user]
  # After this, first_or_create will call user.create, so you don't have to
end

Since your use case is a little more complicated, it may not hurt to split this up into two separate actions. If you want this to occur atomically, you can throw it in a transaction.

User.transaction do
  # Create the user if they don't already exist
  @user = User.where(:email => params[:user][:email]).first_or_create

  # Update with more attributes, and create nested submissions
  @user.update_attributes(params[:user])
end

Hey I think it should be something like that

@user = User.first_or_create(params[:user])

Then in user model

def first_or_create(params)
  unless user = User.where(:email => params[:email]).first # try to find user
    user = User.create(email: params[:user]) 
    # it should create also submission because of accepts_nested_attributes_for 
  else #user exsists so we need to create submission for him
    user.submissions.create(params[:submissions])
  end
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!