Search code examples
ruby-on-railsrubyactiverecord

How to pass hash values of ActiveRecord::Base class


I have method that accept a keyword argument.

def foo(name:)
  p name
end

And I have a ActiveRecord::Base subclass Person that have a name attribute.

Now I'm using method by foo(name: person.name).

But I want to call the method like foo(person.slice(:name)) or foo(person.attributes), because there are some other keyword arguments.

I found out that person.slice(:name) returns like {"name": "Someone"}. The key is string not a symbol, that causes error.

How can I create a hash that have symbol keys? Maybe better way to accomplish what I want to?


Solution

  • That's just how ActiveRecord stores attributes. What you want is:

    person.slice(:name).symbolize_keys
    

    If you're doing this frequently you might want to patch ActiveRecord:

    def symbolized_slice(*args)
      slice(*args).symbolize_keys
    end
    

    I didn't recognize that new notation for keyword arguments in Ruby 2.1. Interesting.