Jashwant
Jashwant

Reputation: 29025

Rails 3.2.8 insert or update based on condition

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 ?

Upvotes: 1

Views: 1354

Answers (2)

Dipak Panchal
Dipak Panchal

Reputation: 6036

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

Upvotes: 0

Frederick Cheung
Frederick Cheung

Reputation: 84182

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)

Upvotes: 6

Related Questions