Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
You know, for objects.
require 'active_support/core_ext/hash/keys'
# Intended as an extension for an ActiveRecord model. It allows construction
# of a valid ActiveRecord object from a Hash, including proper handling of
# the :id attribute.
module ActiveRecordFromHash
def from_hash(hsh)
hsh = hsh.symbolize_keys
self.new.tap do |obj|
# use []= to skip AR setter checks for :id
obj[:id] = hsh.delete(:id)
# use regular method setters for all other attributes
hsh.each do |k,v|
obj.send(:"#{k}=", v)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.