Ruby on rails ActiveRecord:在模型内更改和保存对象状态
我有以下代码:Ruby on rails ActiveRecord:在模型内更改和保存对象状态,ruby-on-rails,ruby,activerecord,models,instance-variables,Ruby On Rails,Ruby,Activerecord,Models,Instance Variables,我有以下代码: def incoming_acceptation(incoming_code) if invite_code == incoming_code accepted = true self.save true else false end end 但它不会更改并保存为true,它仍保持在以前的状态,即false @i.incoming_acceptation(incoming_code) => t
def incoming_acceptation(incoming_code)
if invite_code == incoming_code
accepted = true
self.save
true
else
false
end
end
但它不会更改并保存为true,它仍保持在以前的状态,即false
@i.incoming_acceptation(incoming_code) => true
@i.accepted => false
我建议:
def incoming_acceptation(incoming_code)
update_attribute(:accepted, true) if invite_code == incoming_code
end
update\u属性
将更改并保存该属性。还有一个update\u attributes
(注意s
)可以接受散列来同时更改多个属性:
@obj.update_attributes(:accepted => true, :accepted_at => Time.now)
注意:
update\u attribute
和update\u attributes
在更改和保存成功时都返回true
,就像您的示例一样。我尝试了一个不起作用的。。。然后我就糊涂了。无论如何,谢谢。值得指出的是,如果没有self.
,accepted
被解释为incoming\u acception
中的局部变量,因此赋值不会更改属性值。
@obj.update_attributes(:accepted => true, :accepted_at => Time.now)