Rails 3.2.8 insert or update based on condition

亡梦爱人 提交于 2019-12-13 01:04:44

问题


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

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

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


回答1:


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)



回答2:


try this way

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


来源:https://stackoverflow.com/questions/12988091/rails-3-2-8-insert-or-update-based-on-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!