ironsand
ironsand

Reputation: 15151

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?

Upvotes: 2

Views: 162

Answers (2)

Lev Lukomskyi
Lev Lukomskyi

Reputation: 6667

for recent versions of rails you can extend ActiveRecord this way:

class ApplicationRecord < ActiveRecord::Base
  primary_abstract_class

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

end

Usage:

Person.last.sym_slice(:name, :email) #=> { name: 'John', email: '[email protected]' }

Upvotes: 0

tadman
tadman

Reputation: 211570

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.

Upvotes: 2

Related Questions