我在PostgeSQL数据库中定义了2个hstore列(parameters
和keys
)我想得到一个键列表,并在模型中为它定义了一个方法:
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
但当我尝试使用它时,我会得到以下错误:
NoMethodError: undefined method `each' for #<Class:0x00000004b630b0>
有人能告诉我错误在哪里吗?或者怎么做?
最佳答案
ActiveRecord::Base
不定义.each
方法您需要添加对all
的呼叫,如下所示:
all.each do |log|
#...
end
这应该使
Log.keys_list
和Log.where(name: "Peeyush").keys_list
都能工作。关于ruby-on-rails - Rails遍历模型中的记录,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24326981/