activerecord查找和更新

0xS*_*ina 4 ruby activerecord

在ActiveRecord :: Base上有一个方法find_and_update方法,它基本上会通过它的id找到一条记录并更新一个给定的密钥吗?这将避免必须查询然后更新导致2个查询而不是1.

谢谢

小智 6

活动记录中有一种更新方法,它通过id和updates属性查找.但是这会产生两个sql查询.

update(id, attributes)
Run Code Online (Sandbox Code Playgroud)

例如

 Post.update(params[:id], {:title => 'Hello world'})
Run Code Online (Sandbox Code Playgroud)

如果你不想要验证,你可以使用

Post.update_all({:title => 'hello1'}, {:id => params[:id]})
Run Code Online (Sandbox Code Playgroud)

这将只进行一次SQL查询


小智 6

User.where(id: id).update_all(foo: bar)
Run Code Online (Sandbox Code Playgroud)

This generates only one query.