我有一个通过远程 Web API 检索的 Ruby 哈希。我有一个 ActiveRecord 模型,它具有与散列中的键相同的属性。 Ruby on Rails 4 是否有一种简单的方法可以将散列中的键/值对分配给模型实例?是否可以忽略不存在的键?
最佳答案
super 简单!
更新属性而不保存:
model.attributes = your_hash
# in spite of resembling an assignemnt, it just sets the given attributes
更新属性保存:
model.update_attributes(your_hash)
# if it fails because of validation, the attributes are update in your object
# but not in the database
更新属性,保存,如果无法保存则引发
model.update_attributes!(your_hash)
关于ruby - 如何获取键/值对的哈希值并使用它设置 ActiveRecord 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20462768/