How to take a hash of key/val pairs and set ActiveRecord attributes with it
activerecord, ruby, ruby-on-rails-4
Solution
Super-easy!
Update the attributes without saving:
model.attributes = your_hash
# in spite of resembling an assignemnt, it just sets the given attributes
Update attributes saving:
model.update_attributes(your_hash)
# if it fails because of validation, the attributes are update in your object
# but not in the database
Update attributes, save, and raise if unable to save
model.update_attributes!(your_hash)
Problem
I have a Ruby hash that I'm retrieving via a remote web API. I have an ActiveRecord model that has the same attributes as the keys in the hash. Is there a trivial way with Ruby on Rails 4 to assign the key/val pairs from the hash to the model instance? Is it possible to ignore the keys that do not exist?