ran*_*its 4 ruby activerecord ruby-on-rails-4
我有一个 Ruby 哈希值,正在通过远程 Web API 检索它。我有一个 ActiveRecord 模型,它具有与哈希中的键相同的属性。Ruby on Rails 4 是否有一种简单的方法可以将哈希中的键/值对分配给模型实例?是否可以忽略不存在的键?
超级简单!
更新属性而不保存:
model.attributes = your_hash
# in spite of resembling an assignemnt, it just sets the given attributes
Run Code Online (Sandbox Code Playgroud)
更新属性保存:
model.update_attributes(your_hash)
# if it fails because of validation, the attributes are update in your object
# but not in the database
Run Code Online (Sandbox Code Playgroud)
更新属性,保存,无法保存则提升
model.update_attributes!(your_hash)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4717 次 |
| 最近记录: |