Non persistent ActiveRecord model attributes

Of course use good old ruby's attr_accessor. In your model:

attr_accessor :foo, :bar

You'll be able to do:

object.foo = 'baz'
object.foo #=> 'baz'

I was having the same problem but I needed to bootstrap the model, so the attribute had to persist after to_json was called. You need to do one extra thing for this.

As stated by apneadiving, the easiest way to start is to go to your model and add:

attr_accessor :foo

Then you can assign the attributes you want. But to make the attribute stick you need to change the attributes method. In your model file add this method:

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

In case anyone is wondering how to render this to the view, use the method arguments for the render method, like so:

render json: {results: results}, methods: [:my_attribute]

Please know that this only works if you set the attr_accessor on your model and set the attribute in the controller action, as the selected answer explained.