Rails 3.2.8根据条件插入或更新

我是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是否有一些神奇的东西在一行中做到这一点?

我没有将email声明为主键,但它将是唯一的。 它会帮助我宣布它是主要的吗?

您的代码不起作用,因为要save的参数是选项的散列(例如应运行validation),而不是属性的更改。 你可能想要update_attributes! 代替。 我通常会写类似的东西

 User.where(:email => params[:email]).first_or_initialize.update_attributes!(params) 

试试这种方式

 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