Rails update_attributes 方法是更新数据库模型的最佳选择吗? [英] Is the Rails update_attributes method the best choice for doing an update of a model in the database?
问题描述
def 更新@album = Album.find(params[:id])如果@album.update_attributes(params[:album])redirect_to(:action=>'list')别的渲染(:动作=>'编辑')结尾结尾
我正在介绍的 Rails 1.1.6 教程建议使用 update_attributes
方法来更新模型,就像上面列出的控制器中的示例代码一样.查看 Rails 文档,我想知道为什么不首选 update
方法,特别是因为它的命名如此合乎逻辑.
Update 接受一个对象 id
参数和一组属性,这些属性的工作方式类似于 update_attributes
.>
所以这个(来自 AWDWR 第三版)
Order.update(12, :name => "Barney", :email => "barney@bedrock.com")
相当于
Order.find(12).update_attributes(:name => "Barney", :email => "barney@bedrock.com")
因此,如果您只想用一组属性更新一行已知 id,那么我会说没有理由不使用 update
- 看起来这就是他们写的原因它!
(有什么办法可以让你的教程从 1.1.6 升级?它已经很老了,并且在它最新时并不是一个特别惊天动地的版本.1.2.6 更好 - 1.1.6 中的最后一个.xs,如果我没记错的话).
def update
@album = Album.find(params[:id])
if @album.update_attributes(params[:album])
redirect_to(:action=>'list')
else
render(:action=>'edit')
end
end
A Rails 1.1.6 tutorial that I'm covering recommends using the update_attributes
method for updating a model, as in the example code from my controller listed above. Looking at the Rails documentation I'm wondering why the update
method would not have been preferred, especially since it is named so logically.
Update takes an object id
parameter and a set of attributes that otherwise work like update_attributes
.
So this (from AWDWR 3rd edition)
Order.update(12, :name => "Barney", :email => "barney@bedrock.com")
is equivalent to
Order.find(12).update_attributes(:name => "Barney", :email => "barney@bedrock.com")
So if all you want to do is update a row of known id with a set of attributes then I'd say there's no reason not to use update
- it looks like that's the reason they wrote it!
(Is there any way you can get your tutorial to upgrade from 1.1.6? It's pretty old and wasn't a particularly earth-shattering release when it was current. 1.2.6 was better - the last of the 1.xs, if I remember correctly).
这篇关于Rails update_attributes 方法是更新数据库模型的最佳选择吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!