如何从ActiveRecord列数组中一般获取列的值?

时间:2014-01-26 03:39:27

标签: ruby-on-rails activerecord

我正在尝试编写任意表数据的通用转储器/输出器,而不必单独指定每个属性。因此可以指定一个对象(表),但属性应该自己处理(可能需要按数据类型进行一次性格式化)。

class ArbitraryRecordObject < ActiveRecord::Base
  # let ArbitraryRecordObject have an arbitrary list of attributes (mapping to db columns)
  # of type int, float, strings, dates and timestamps
end

我正在尝试执行以下操作,而没有明确指定属性(即列)名称

for all instances of ArbitraryRecordObject (ie for each row in the arbitrary_record_objects table)
  for each column in each instance (ie each row)
    puts column.name + row.column.value.to_s # column.name works but don't know how to get the value
  end
end

有没有办法实现这一目标?感谢。

2 个答案:

答案 0 :(得分:0)

ArbitraryRecordObject.all.each do |o|
  o.attributes.each do |key, value|
    puts "#{key}: #{value}"
  end
end

答案 1 :(得分:0)

另一种方式......

column_names = ArbitraryRecordObject.column_names

ArbitraryRecordObject.all.each do |row|
  column_names.each do |col_name|
    puts "#{col_name} #{row.send(col_name)}"
  end
end