Rails 3.2.8 根据条件插入或更新 [英] Rails 3.2.8 insert or update based on condition

查看:39
本文介绍了Rails 3.2.8 根据条件插入或更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Rails 的新手,正在使用此代码更新或插入.

I am new to Rails and using this code to update or insert.

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

This code is not working. Also, I would like to know if Rails has something magical to do this in one line ?

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

I've not declared email as primary key but its going to be unique. Will it help me to declare it as primary ?

推荐答案

您的代码不起作用,因为 save 的参数是选项的散列(例如是否应该运行验证),而不是属性的变化.您可能需要 update_attributes! 来代替.我通常会写一些类似的东西

Your code doesn't work because the parameter to save is as a hash of options (such as should validations run), not the changes to the attributes. You probably want update_attributes! instead. I would usually write something like

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

这篇关于Rails 3.2.8 根据条件插入或更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆