Rails update_attributes方法是在数据库中更新模型的最佳选择吗? [英] Is the Rails update_attributes method the best choice for doing an update of a model in the database?

查看:453
本文介绍了Rails update_attributes方法是在数据库中更新模型的最佳选择吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  def update 
@album = Album.find(params [:id])
if @ album.update_attributes(params [:album])
redirect_to(:action =>'list')
else
render(:action =>'edit')
end
end

我覆盖的Rails 1.1.6教程建议使用 update_attributes 方法用于更新模型,如上面列出的我的控制器的示例代码。查看Rails文档我想知道为什么更新方法不会是首选,特别是因为它被命名为逻辑。

id 参数和一组属性,否则工作类似 update_attributes



这样(从 AWDWR第3版

 订单.update(12,:name =>Barney,:email =>barney@bedrock.com)


b $ b

等效于

  Order.find(12).update_attributes(:name =>Barney ,:email =>barney@bedrock.com)

用一组属性更新一行已知的id然后我会说没有理由不使用 update - 它看起来像这样写的原因!



(有没有办法让你的教程从1.1.6升级?它很旧,当它是最新的时,不是一个特别地球爆发释放。 1.2.6是更好的 - 1.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆