Ruby on Rails |设置属性

时间:2012-02-11 08:23:53

标签: ruby-on-rails

除了使用attribute=之外,还有其他方法可以在Rails中设置模型的属性吗?

例如,是否有类似set_attribute(name, value)的内容?

user = User.new
user.set_attribute(:name, 'Jack')
user.set_attribute(:surname, 'The Ripper')
user.save

# instead of
user.name = 'Jack'
user.surname = 'The Ripper'

2 个答案:

答案 0 :(得分:3)

寻找我们能找到的AR来源

# File activerecord/lib/active_record/persistence.rb, line 208
def update_attributes(attributes, options = {})
  # The following transaction covers any possible database side-effects of the
  # attributes assignment. For example, setting the IDs of a child collection.
  with_transaction_returning_status do
    self.assign_attributes(attributes, options)
    save
  end
end

因此您可以使用assign_attributes(attributes, options)设置属性而不保存

此外,如果您想按名称设置属性而不直接调用方法,则可以使用 user.send(:name=, 'Jack')代替user.set_attribute(:name, 'Jack')

答案 1 :(得分:2)

有一种write_attribute方法。它应该是你正在寻找的。

修改

如果您想一次更新多个属性,可以使用update_attributes