Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails update_attributes not working for Postgresql

In my Rails project I am using Postgresql.

User.find_by_sql("update users set address = '#{params[:address]}' where id = #{current_user.id}")

This code is working fine, but the equivalent activerecord is not working :

   user = User.find(current_user.id)
   user.update_attributes(:address => params[:address])

it always shows Begin; Rollback in log. Can you please explain why is this happening? Is there any issue related to Postgres? I am using Rails 3.2

EDIT

I found out where i was wrong... a validation fail was causing this. The solution is :

  user.update_column(:address,params[:address])

This will bypass validation. Thank you guys for help.

like image 452
sunny1304 Avatar asked Apr 20 '26 23:04

sunny1304


2 Answers

update_attributes updates the record if all the validations pass, so one of your validation must have failed, use user.errors to find out the errors:

user = User.find(current_user.id)
user.update_attributes(:address => params[:address])
puts user.errors

In order to save a single column, use update_attribute.

user.update_attribute(:address, params[:address])
like image 177
Salil Avatar answered Apr 24 '26 08:04

Salil


check for failures:

user.update_attributes!(...)
like image 34
Martin M Avatar answered Apr 24 '26 09:04

Martin M