简体   繁体   English

如何在不使用不同变量名的情况下更新 rails model 实例方法中的属性?

[英]How do you update attributes in an instance method in a rails model without using different variable names?

I would like to update attributes in an instance method in rails without being forced to change the parameters being passed in so that I can advantage of rails automatic attributes.我想在 rails 的实例方法中更新属性,而不必被迫更改传入的参数,以便我可以利用 rails 的自动属性。 Here is an example.这是一个例子。

Ideal:理想的:

status = "some_new_status"
person.update(status)

class Person < ActiveRecord::Base
  def update(status)
    self.status = status
  end
end

What I have to do now:我现在必须做的:

class Person < ActiveRecord::Base
  def update(new_status)
    self.status = new_status
    self.save
  end
end

I understand in this example it doesn't much matter.我明白在这个例子中它并不重要。 But when I have complicated update methods, it would be a lot cleaner if I could eliminate some of that code.但是当我有复杂的更新方法时,如果我能删除一些代码会干净得多。

You should use builtin Rails methods:你应该使用内置的 Rails 方法:

@person.update_attribute(:status, "Some Value") #no callback triggered nor validation

@person.update_attributes(:status => "Some Value") #can pass multiple values

Or to keep your short syntax或者保持你的简短语法

def update(status)
  update_attribute(:status, status)
end

Update_attribute doc.更新属性文档。

Update_attributes doc.更新属性文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM