1

I have 2 hstore columns (parameters and keys) defined in my PostgeSQL database. I want to get a list of keys and have defined a method for it in the model:

def self.keys_list
  logs = self
  list = Log.column_names - %w{id parameters extras}
  logs.each do |log|
    log.parameters.present? ? list << log.parameters.keys : list << []
    log.extras.present? ? list << log.extras.keys : list << []
  end
  list = list.flatten.uniq
  return list
end

But when I try using it, I get the following error:

NoMethodError: undefined method `each' for #<Class:0x00000004b630b0>

Can anyone suggest where the error is or how to do it some other way?

5
  • logs = self; logs.each... self in this case would be the class that you are in so logs has been set to a class, perhaps you meant to set it to something else? Commented Jun 20, 2014 at 12:14
  • Let's say I have some logs. logs = Log.where(name: "Peeyush"). Now, I would like to get the list of keys for it. So, I want to make a call like logs.keys_list on it. Commented Jun 20, 2014 at 12:17
  • logs.map{|a| a.keys_list}.flatten I think would do it.. of course that expects Log to have defined a keys_list function for each individual log... Commented Jun 20, 2014 at 12:21
  • The logs = self bit is very confusing. Just use self. Commented Jun 20, 2014 at 12:40
  • 1
    I think you want what Matijs' answer suggests. Though, I would like to suggest one off topic.. You can write log.parameters.present? ? list << log.parameters.keys : list << [] as list << log.parameters.present? ? log.parameters.keys : []. It removes the repetition and looks nice. Commented Jun 20, 2014 at 12:42

1 Answer 1

5

ActiveRecord::Base does not define an .each method. You need to add in a call to all, like so:

all.each do |log|
  #...
end

This should make both Log.keys_list and Log.where(name: "Peeyush").keys_list work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.