0

I created a Rails model, let's say Car. I added an attribute to it (not to be saved in the DB) called age.

class Car < ActiveRecord::Base
  attr_accessor :age 
end

If I try to print out the attributes of my car, age does not show up. I found out because attr_accessor is only defining an instance variable.

> my_car = Car.first
> my_car.age = 500
> puts my_car

How can I add an attribute to the record itself that is not persisted to the DB?

Don P
  • 60,113
  • 114
  • 300
  • 432
  • you just answered your own question. – sevenseacat Aug 06 '14 at 01:20
  • @sevenseacat thanks, wasn't sure if that was it. Updated question, since I still need to know how to add an attribute to the record without persisting it to db. – Don P Aug 06 '14 at 01:26
  • you already have - you use `attr_accessor`. Just because it isn't output in the `inspect` output, doesn't mean it doesn't exist. – sevenseacat Aug 06 '14 at 01:28
  • I do `my_car.to_json` and I need `age` to be included. – Don P Aug 06 '14 at 01:31
  • 2
    hooray, now we get the actual problem. Define `as_json` in your model to specify the required json representation of the model. – sevenseacat Aug 06 '14 at 01:34
  • This question is not useful in it's current form. `attr_accessor` **does** add a field which isn't saved to the database. – user229044 Aug 06 '14 at 03:41

1 Answers1

0

Referce of to_json

Render age to json with methods option.

my_car = Car.first
my_car.age = 500
puts my_car.to_json(:methods => :age)
Jaugar Chang
  • 3,176
  • 2
  • 13
  • 23