Update_attributes


#1

I am trying to do a simple update to a model. I think that I am
making the call correctly, however the update is not made. Looking at
the development.log, I see that when I try to make an
update_attributes call, the following is SQL call is made:

SELECT * FROM users WHERE (users.name = ‘sara’ AND users.id <> 9)
LIMIT 1

Since the users.name does = ‘sara’ and the users.id is ‘9’ the update
query does not run.

My question is WHY DOES THIS SELECT QUERY get run in the first place

Here is my controller code for running the update:

def update_user

@update = User.find(params[:id])

if @update.update_attributes(params[:user])
  flash[:notice] = "User #{params[:user][:name]} updated

successfully"
else
flash[:notice] = “Error in updating record”
end

redirect_to(:action => 'list_users')

end

and the entire log entry when this controller is called:

Processing AdminController#update_user (for 127.0.0.1 at 2007-02-20
12:25:31) [POST]
Session ID: 236e817b752befbe3c15e1c78e8a3596
Parameters: {“user”=>{“name”=>“sara”, “user_type”=>“nelnet”,
“user_role”=>“super”}, “commit”=>" Update User ",
“action”=>“update_user”, “id”=>“9”, “controller”=>“admin”}
[4;36;1mUser Load (0.000452) [0m [0;1mSELECT * FROM users WHERE
(users.id = ‘9’) LIMIT 1 [0m
[4;35;1mUser Columns (0.002539) [0m [0mSHOW FIELDS FROM
users [0m
[4;36;1mSQL (0.001285) [0m [0;1mBEGIN [0m
[4;35;1mUser Load (0.000522) [0m [0mSELECT * FROM users WHERE
(users.name = ‘sara’ AND users.id <> 9) LIMIT 1 [0m
[4;36;1mSQL (0.000094) [0m [0;1mCOMMIT [0m
Redirected to http://localhost:3000/admin/list_users
Completed in 0.01411 (70 reqs/sec) | DB: 0.00489 (34%) | 302 Found
[http://localhost/admin/update_user/9]


#2

namwob wrote:

My question is WHY DOES THIS SELECT
QUERY get run in the first place

Have you got any validations in the model?


#3

Further note:

If I comment out this line in my user.rb model file

validates_uniqueness_of :name

#validates_presence_of :name, :password

The SQL query in question still runs, but then the UPDATE query runs
successfully.

I am totally lost as to the reason behind this. Any thoughts would be
much appreciated.

Thanks,

-E


#4

Messages were delivered out of sequence.

namwob wrote:

If I comment out this line in my user.rb model file

validates_uniqueness_of :name

I think it’s because an update is a save and validates_uniqueness_of is
just
doing what you asked it to do which is to disallow a save if a record
already exists that meets that criteria. Maybe it should be smarter.
In
the meantime, you can add an :except condition to your validation for
the
update.

hth,
Bill