tommyd456
tommyd456

Reputation: 10703

update query with where clause

very simple question - I want to update one record only that matches 2 parameters.

Should I be doing it like this:

Model.where(:email =>"[email protected]",:code => "chejd").update(:password => "password").first

I have found examples using update_all but I only want to update a maximum of 1 record.

Upvotes: 7

Views: 26891

Answers (2)

Jaiganesh
Jaiganesh

Reputation: 17

Similar to above answer. If you want to update either the first or last record, you can append that and can run the query.

Model.where(conditions).first.update(changes) or Model.where(conditions).last.update(changes)

first - fetches the first record ordered by primary key last - fetches the last record ordered by primary key

Upvotes: 0

kristinalim
kristinalim

Reputation: 3459

Check if this works with your DBMS and DB adapter:

Model.where(conditions).limit(1).update_all(changes) # => 1

Update:

The limit() and update_all() combo is an example in the docs, so it's probably supported by most DB adapters.

Upvotes: 24

Related Questions