开发者

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?


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜