Looping on attributes of an inactive record model object

An easy way to iterate over all the attributes of an object when using Active Record is

order_item_object.attributes.each do |key,value|
....
end

But this does not work when we do not use Active Record. How can I iterate over all attributes of an object?

For example, for: -: I have a model in Rails that does not use an active record. The object from the order_item model can be used in the controller, for example order_item_object.product_id, order_item_object.quantity, order_item_object.quoted_price. But when I try order_item_object.attributes.each do |k,v|.... I getundefined method "attributes" for #<Order:0x00000005aa81b0>

How should I do it?

+5
source share
6 answers

This is the best way to find

item=self.instance_values.symbolize_keys
item.each do |k,v|
  ...
  ..
end

( ) -

+1

:

class Parent
  def self.attr_accessor(*vars)
    @attributes ||= []
    @attributes.concat vars
    super(*vars)
  end

  def self.attributes
    @attributes
  end

  def attributes
    self.class.attributes
  end
end

class ChildClass < Parent
  attr_accessor :id, :title, :body
end

p ChildClass.new.attributes.inspect #=> [:id, :title, :body]
+3

attr_accessor - , . SO, , instance_variables, ,

class Foo
  attr_accessor :bar
  attr_accessor :baz
end

foo = Foo.new
foo.bar = 123
foo.baz
foo.instance_variables.each do |ivar_name|
  ivar_value = foo.instance_variable_get ivar_name
  # do something with ivar_name and ivar_value
end

. ActiveRecord . . , , . @saved, , .

, ?

+3

, :

self.instance_values.keys.each do |k|
 ..
end

( ), .

+1

, , ActiveRecord, db .

Record , , . , instance_variables, , .

0

:

class Test
  attr_accessor :firstname,:lastname
  def initialize(fn,ln); @firstname = fn; @lastname = ln; end
end

o = Test.new("Fernando", "Mendez")
o.instance_variables.each {|e| p o.send e.to_s.sub("@","").to_sym}
output:
"Fernando"
"Mendez"

-:

r = o.instance_variables.map {|e| Hash[e,(o.send e.to_s.sub("@","").to_sym)]}

#[{:@firstname=>"Fernando"}, {:@lastname=>"Mendez"}]
0

All Articles