0

Let's say that a person table/model has id and name:

class Person < ActiveRecord::Base

  def height
    return '10 feet tall'
  end

end

How do I allow it to return the 'height' method in the results so that instead of this:

=> #<Person id: 1, name: "bob">

It is this:

=> #<Person id: 1, name: "bob", height: "10 feet tall">
oprogfrogo
  • 2,005
  • 5
  • 31
  • 42

2 Answers2

0

You can use ruby class attributes via attr_accessor method. But it will be not a really fields in DB. For example you need field height use something like this

class Person < ActiveRecord::Base 

  attr_accessor :height 
  def height 
    return @height
  end 
  def height=(val)
    @height = val
  end
end 

and you can use it like (for example if you have Person with id 1)

Person.find(1).height
Alexander Kobelev
  • 1,379
  • 8
  • 14
  • Hello, and thanks for taking the time, but that example does not work for me. I still do not see the 'height' key/value being returned in the results. – oprogfrogo Jun 17 '14 at 21:01
  • you see real db fields in console - but you want to add something like virtual field - so when you retrieve record from db, you cannot see methods from model, but you can use them like after retrieved object from DB - Person.first.my_method. Maybe this answer will be useful for you http://stackoverflow.com/questions/1289557/how-do-you-discover-model-attributes-in-rails – Alexander Kobelev Jun 17 '14 at 21:06
  • Maybe I should've given more detail, the results of the find will be a json response to a different app that is calling this. So it needs to have all the key/values in the json object. – oprogfrogo Jun 17 '14 at 21:12
  • for json serialization you can use methods and fields from model - by overriding as_json method of ActiveModel http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html - or use some gems (jbulder or rabl for example to do more MVC in your project) – Alexander Kobelev Jun 17 '14 at 21:18
0

What seems to work is this below:

attr_accessor :height

def attributes
    super.merge('height' => self.height)
end

def height
    '10 feet tall'
end

Is there a better minimal code way to do this?

oprogfrogo
  • 2,005
  • 5
  • 31
  • 42