RameshVel
RameshVel

Reputation: 65867

Rails way to update the data based on the conditions

What's the best way to update table values based on some given condition in activerecord? I have tried this

  Suggestion.update(:active => 1).where({:item_id => 2, :user_id => 100})

but it is not working. Update method expects another parameter (id). If I change the query like this,

  suggest = Suggestion.where({:item_id => 2, :user_id => 100}).select(:id)
  id = suggest.first.id
  Suggestion.Update(id,:active => 1)

this completely blows me. Why do I have to make two calls to db to update a record where it can be done in a single update call?

Upvotes: 1

Views: 1370

Answers (1)

Vlad Khomich
Vlad Khomich

Reputation: 5880

Suggestion.update_all({:active => 1}, {:item_id => 2, :user_id => 100})

=>

UPDATE "suggestions" SET "active" = 1 WHERE ("suggestions"."item_id" = 2) AND ("suggestions"."user_id" = 100)

Upvotes: 6

Related Questions