打印

update_attributes()是出错

update_attributes()是出错

按照depot里写的user模型类,输入password后会自动生成hashed_password。

我的users表里还有其它的字段:address, email。

我在controller里用update_attributes()方法更新address和email这2个字段,代码如下:

user = User.find(1)
user.update_attributes!(:address => "abc", :email => "abc@hot.com")


结果出现错误 Validation failed: Password can't be blank。

可我不想更新password,这个字段,请问该怎样解决?

TOP

update_attributes需要后面那个“!”吗?
好像没有 update_attributes! 这个方法吧!

user.update_attributes(:address => "abc", :email => "abc@hot.com")

TOP

update_attributes!会被转换成save!

如果不加update_attributes!,数据是不会更新的,也不会抱错,加了"!"就显示错在哪了

TOP

难道我们的版本不同,我使用的时候确实没有“update_attributes!”这个方法呢!为什么呢?

>> item = Item.find(1)
=> #<Item:0x3939fb0 @attributes={"name"=>"test", "lock_version"=>"6", "id"=>"1",
 "version"=>"8", "category_id"=>"1", "description"=>"tewefsdf adf\r\ndfadsf adf
", "created_at"=>"2007-11-10 14:09:18"}>
>> item.update_attributes!(:name=>"test update",:category_id=>"2")
NoMethodError: undefined method `update_attributes!' for #<Item:0x3939fb0>
        from c:/ruby/lib/ruby/gems/1.8/gems/activerecord-1.14.4/lib/active_recor
d/base.rb:1792:in `method_missing'
        from (irb):2


TOP

最近真的是懒得想这个问题,今天突然有心情了,仔细地琢磨了一下,问题解决了。

在更新时,不用update_attributes()或save()。而是用update_attribute(),逐个更新。

Ex:
@user = User.find(1)
if request.post?
@user.update_attribute(:name, "kelly")
@user.update_attribute(:group, 0)
end

这样写,就不会报错,password can't be blank了
本帖最近评分记录
  • drive2me R币 +5 谢谢! 2008-4-6 08:52

TOP

引用:
原帖由 bob21 于 2008-4-6 02:10 发表
最近真的是懒得想这个问题,今天突然有心情了,仔细地琢磨了一下,问题解决了。

在更新时,不用update_attributes()或save()。而是用update_attribute(),逐个更新。

Ex:
@user = User.find(1)
if request.p ...
但是什么原因搞得不能用update_attributes()或save(),而只能用update_attribute()来逐个更新呢。
似乎是怪问题?Bug?
Flying Piggy...! 
天地人合一!

TOP

在表里存的是hashed_password,但是这数据是由用户填入password后由model自动创建的,所以一更新其它的数据,model就会运行那个创建hashed_password方法。

但是我也不是很明白为什么单个的更新就没事,更新2个以上就会有问题

TOP

注释
# Updates all the attributes from the passed-in Hash and saves the record. If the object is invalid, the saving will
# fail and false will be returned.

代码
self.attributes = attributes
save

保存的是self.attributes就是我们传进去的hash, 所以貌似这儿要更新就要写上所有的字段.
------------------------------------------------

而update_attribute 只改一个字段其它的是不变的.
send(name.to_s + '=', value)
save
------------------------------------------------

所以我想可行的办法是取属性hash, 改动几个属性, 再传回去用update_attributes()更新

参考
http://qiezi.javaeye.com/blog/26630

[ 本帖最后由 5swords 于 2008-4-9 18:41 编辑 ]
本帖最近评分记录
  • bob21 R币 +3 谢谢赐教 2008-4-15 07:44

TOP

user.update_attributes!(user[:address] => "abc", user[:email] => "abc@hot.com")
这样试试。

TOP

回复 8# 的帖子

有些道理,但还是有些疑惑

等我研究研究

TOP

class User < ActiveRecord::Base
validates_presence_of :password, :if new_record?
attr_accessor :update_password
def new_record?
 update_password
end
控制器里面这样写
@user.update_password=false //不验证
@user.update_password=true //验证

TOP

2008-11-23 23:31 Crawled by CCBot/1.0 (+http://www.commoncrawl.org/bot.html) @38.103.63.61