Ruby-on-rails Rails update_attributes 方法是更新数据库模型的最佳选择吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/840199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:13:44  来源:igfitidea点击:

Is the Rails update_attributes method the best choice for doing an update of a model in the database?

ruby-on-railsmodelcontrollerupdatemodelupdate-attributes

提问by pez_dispenser

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_attributesmethod for updating a model, as in the example code from my controller listed above. Looking at the Rails documentation I'm wondering why the updatemethod would not have been preferred, especially since it is named so logically.

我正在介绍的 Rails 1.1.6 教程建议使用update_attributes更新模型的方法,如上面列出的控制器中的示例代码。查看 Rails 文档,我想知道为什么该update方法不是首选,特别是因为它的命名如此合乎逻辑。

回答by Mike Woodhouse

Update takes an object idparameter and a set of attributes that otherwise work like update_attributes.

更新采用一个对象id参数和一组属性,否则像update_attributes.

So this (from AWDWR 3rd edition)

所以这个(来自AWDWR 3rd edition

Order.update(12, :name => "Barney", :email => "[email protected]")

is equivalent to

相当于

Order.find(12).update_attributes(:name => "Barney", :email => "[email protected]")

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!

因此,如果您只想用一组属性更新一行已知 ID,那么我会说没有理由不使用update- 看起来这就是他们编写它的原因!

(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).

(有什么办法可以让你的教程从 1.1.6 升级?它已经很老了,而且在它最新时并不是一个特别惊天动地的版本。1.2.6 更好 - 1.xs 的最后一个,如果我没记错)。

回答by babttz

Using update_attributes method just suppose that you already have an object, and you would just pass the set of attributes. And the work is done !

使用 update_attributes 方法只是假设您已经有一个对象,并且您只需传递一组属性。工作完成了!