1

私は Rails を初めて使用し、このコードを使用して更新または挿入します。

user = User.find_by_email(params[:email])
if user.nil?
  User.create!(params)
else
  user.save(params)
end 

// params is a hash with keys as table columns

このコードは機能していません。また、Rails にこれを 1 行で行う魔法のような機能があるかどうかを知りたいですか?

email主キーとして宣言していませんが、一意になります。それを primary として宣言するのに役立ちますか?

4

2 に答える 2

0

この方法を試してください

user = User.find_by_email(params[:email])  # if you receive email in params[:email]
unless user.present?
  @user = User.create!(params[:user]) # params[:user] replace with whatever you receive all your attributes 
else
  @user = user # here if your want to update something you can do it by using update attributes
end
于 2012-10-20T12:09:59.890 に答える